No type named 'type' in CTRP derived class

后端 未结 4 563
猫巷女王i
猫巷女王i 2020-12-31 11:22

I\'ve been experimenting with the Curiously Recurring Template Pattern for a generic single-argument functor and have two implementations: one using a template template para

4条回答
  •  無奈伤痛
    2020-12-31 12:15

    When the line

    using Ftype = typename Functor::type;
    

    is processed in the base class, the definition of Functor is not available. Hence, you can't use Functor::type.

    One way to get around this limitation is to define a traits class.

    // Declare a traits class.
    template  struct FunctorTraits;
    
    template
    class FunctorInterface_2 {
       private:
          const Functor &f_cref;
       public:
    
          // Use the traits class to define Ftype
          using Ftype = typename FunctorTraits::type;
    
          FunctorInterface_2() : f_cref(static_cast(*this)) {}
          Ftype operator() ( Ftype val ) const { return f_cref(val); }
    }; // FunctorInterface_2 (no type in Functor!)
    
    // Forward declare Cube to specialize FunctorTraits
    template struct Cube;
    
    // Specialize FunctorTraits for Cube
    template  struct FunctorTraits>
    {
       using type = T; 
    };
    
    template
    struct Cube : public FunctorInterface_2> {
       using type = T; 
       T operator() ( T val ) const { return val*val*val; }
    }; // Cube
    

    Working code: https://ideone.com/C1L4YW

提交回复
热议问题