[英]Using nested class of template parameter in CRTP
Suppose I define a template T
that uses a nested class of the template parameter P
, as follows: 假设我定义了一个模板
T
,它使用模板参数P
的嵌套类,如下所示:
template<class P> class T
{
public:
T(P& p) : p(p) {}
P& p;
typename P::Nested& get_nested() { return p.nested; }
};
If I declare a class A
that includes a nested class named Nested
, I can define a variable of type T<A>
with no problem: 如果我声明一个类
A
,其中包含一个名为Nested
的嵌套类,则可以毫无问题地定义一个T<A>
类型的变量:
class A
{
public:
class Nested
{
public:
int i;
};
Nested nested;
};
void test2a()
{
A a;
a.nested.i = 1;
T<A> t_a(a);
t_a.get_nested().i = 2;
}
Now, I want to declare a class B
that, in the same way, includes a nested class named Nested
and that inherits from T<B>
, as follows: 现在,我想声明一个类
B
,它以相同的方式包括一个名为Nested
的嵌套类,该类继承自T<B>
,如下所示:
class B : public T<B>
{
public:
class Nested
{
public:
int i;
};
Nested nested;
};
Compilation of the above code fails with error: " Nested is not a member of B " 上面的代码编译失败,并显示错误消息:“ 嵌套不是B的成员”
I think I understand what's happening: at the time the template is entered, class B is incompletely defined because of inheritance. 我想我了解发生了什么:在输入模板时,由于继承,未完全定义类B。
However, I am wondering if there is any way to do such a thing... 但是,我想知道是否有任何方法可以做这样的事情...
Thanks for help. 感谢帮助。
You need to defer the resolution of the return type of get_nested
until it is called. 您需要推迟
get_nested
返回类型的get_nested
直到调用它为止。
One way to do this is to make the return type dependent on a template parameter: 一种方法是使返回类型取决于模板参数:
template<typename unused = void>
typename std::conditional<false, unused, P>::type::Nested&
get_nested() { return p.nested; }
Another way (since C++14) is to use return type deduction: 另一种方法(自C ++ 14起)是使用返回类型推导:
auto& get_nested() { return p.nested; }
I was able to have your example compile with simply 我能够简单地编译您的示例
template<class P> class T
{
public:
T(P& p) : p(p) {}
P& p;
auto& get_nested() { return p.nested; }
};
Another approach, exploiting the same trick as @ecatmur, but a bit simpler: 另一种方法,利用了与@ecatmur相同的技巧,但更简单:
template<class R = P>
typename R::Nested& get_nested() { return p.nested; }
Similarly, here the compiler has to postpone evaluation of P::Nested
until you call get_nested()
. 同样,在这里,编译器必须推迟对
P::Nested
求值,直到调用get_nested()
为止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.