使用派生的模板参数类型作为 return 类型的函数(CRTP)?

Use the template parameter type of derived as return type for function (CRTP)?

我在下面的代码中重现了我遇到的问题:

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
};

问题是我需要让 A 有一个 return 类型 T::type 的函数,但是因为在编译 A 时 B 没有完全声明,所以我得到当我尝试编译它时出现错误 invalid use of incomplete type ‘class B<int>’(其中 int 可以替换为任何其他类型)。有什么方法可以让它发挥作用吗?

如果将B<T>::type的定义移动到外部traits-class:

就可以实现
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;
};

Is there any way to get this to work?

您可以使用特征 class 来派生类型,而不是使用:

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;
}