[英]Use the template parameter type of derived as return type for function (CRTP)?
I've recreated the problem I'm having in the code below: 我已经重新创建了以下代码中的问题:
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
};
The problem is that I need to have A have a function with a return type of T::type
, but because B isn't completely declared at the time when A is compiled, I get the error invalid use of incomplete type 'class B<int>'
when I try to compile it (where int could be replaced with any other type). 问题是我需要让A具有返回类型为T::type
的函数,但是由于在A编译时B并未完全声明B,所以我会收到错误消息,错误地invalid use of incomplete type 'class B<int>'
当我尝试对其进行编译时(可以将int替换为任何其他类型)。 Is there any way to get this to work? 有什么办法可以使它正常工作吗?
You can achieve it if you move the definition of B<T>::type
to an external traits-class: 如果将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;
};
Is there any way to get this to work? 有什么办法可以使它正常工作吗?
You can use a traits class to derive the type instead of using: 您可以使用traits类来派生类型,而不是使用:
using type = T::type;
Example: 例:
// 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.