代码之家  ›  专栏  ›  技术社区  ›  BadProgrammer99

是否将派生的模板参数类型用作函数(CRTP)的返回类型?

  •  2
  • BadProgrammer99  · 技术社区  · 7 年前

    我在下面的代码中重新创建了问题:

    template<typename T>
    class A{
        using type = T::type;
        type someFunction(/*some parameters*/){/*code for the function*/}
        //other stuff
    };
    
    template<typename T>
    class B : public A<B<T>>{
        typedef T type;
        //other stuff
    };
    

    T::type ,但因为在编译A时B没有完全声明,所以我得到了错误 invalid use of incomplete type ‘class B<int>’ 当我试图编译它时(int可以被任何其他类型替换)。有什么办法可以让它工作吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Jodocus    7 年前

    如果你移动定义 B<T>::type 对于外部特征类:

    template <typename T>
    struct Traits { /* maybe some default values */ };
    
    template<typename T>
    class A{
        using type = typename Traits<T>::type;
        type someFunction(/*some parameters*/){/*code for the function*/}
        //other stuff
    };
    
    template<typename T>
    class B : public A<B<T>>{
        using type = typename Traits<B<T>>::type;
    };
    
    template <typename T>
    struct Traits<B<T>> {
        using type = T;
    };
    
        2
  •  1
  •   R Sahu    7 年前

    有什么办法可以让它工作吗?

    您可以使用traits类来派生类型,而不是使用:

    using type = T::type;
    

    例子:

    // Declare TypeSelector
    template <typename T> struct TypeSelector;
    
    template <typename T>
    class A
    {
        using type = typename TypeSelector<T>::type;
        type someFunction(/*some parameters*/){ return type {}; }
    };
    
    // Declare B.
    template <typename T> class B;
    
    // Define TypeSelector for <B<T>> first before defining B<T>
    template <typename T> struct TypeSelector<B<T>>
    {
        using type = T;
    };
    
    template<typename T>
    class B : public A<B<T>>{
        using type = typename TypeSelector<T>::type;
        //other stuff
    };
    
    int main()
    {
       // Compiles fine.
       B<int> a;
    }