我已经重新创建了以下代码中的问题:
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具有返回类型为
T::type
的函数,但是由于在A编译时B并未完全声明B,因此我在尝试编译时会收到invalid use of incomplete type ‘class B<int>’
错误(其中int可以被其他类型替换)。有什么办法可以使它正常工作吗? 最佳答案
如果将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;
};
关于c++ - 使用派生的模板参数类型作为函数的返回类型(CRTP)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47345071/