gpt4 book ai didi

c++ - 在 CRTP 中使用嵌套类的模板参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:09 25 4
gpt4 key购买 nike

假设我定义了一个模板 T使用模板参数的嵌套类 P ,如下:

template<class P> class T
{
public:
T(P& p) : p(p) {}
P& p;
typename P::Nested& get_nested() { return p.nested; }
};

如果我声明一个类 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;
}

现在,我要声明一个类 B以同样的方式,包含一个名为 Nested 的嵌套类并且继承自 T<B> ,如下:

class B : public T<B>
{
public:
class Nested
{
public:
int i;
};
Nested nested;
};

上述代码的编译失败并出现错误:“Nested 不是 B 的成员”

我想我明白发生了什么:在输入模板时,类 B 由于继承而未完全定义。

但是,我想知道有没有办法做这样的事情......

感谢您的帮助。

最佳答案

您需要推迟对 get_nested 返回类型的解析,直到它被调用。

一种方法是使返回类型依赖于模板参数:

  template<typename unused = void>
typename std::conditional<false, unused, P>::type::Nested&
get_nested() { return p.nested; }

另一种方式(自 C++14 起)是使用返回类型推导:

  auto& get_nested()    { return p.nested; }

关于c++ - 在 CRTP 中使用嵌套类的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33828787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com