gpt4 book ai didi

c++ - 相互包含的派生和专用模板类

转载 作者:行者123 更新时间:2023-11-30 04:26:53 25 4
gpt4 key购买 nike

我在 header 中有此代码(已编辑):

template <int i> class A {};
template <> class A <1> { B<1> _b; };

template <int i> class B : public A <i> {};
template <> class B <1> : public A <1> {};

并以某种方式像这样使用它:

#include "template_A_B.h"
int main ()
{
A<1> a;
B<1> b;
return 0;
}

显然我得到了编译错误:

error: ‘B’ does not name a type

如果我像这样添加 B 的前向声明

template <int i> class B;

我明白了

error: field ‘_b’ has incomplete type

编译时。

我还尝试向前声明 A 并切换类定义的顺序并得到:

error: declaration of ‘struct A<1>’

最佳答案

在您最初提出的问题中,您只需要将您的特化放在您的前置声明之后。那么一切都会得到正确的解决。

template <int i> class A;
template <int i> class B;

template <> class A <1> {};
template <> class B <1> : public A <1> {};

template <int i> class A { B<1> _b; };
template <int i> class B : public A <i> {};

在您修改后的问题中,您创建了一个试图包含自身的结构,即使对于非模板类型也是不允许的。例如,您不能定义:

struct A { B b; };
struct B : public A {};

但是,如果您将 A 更改为使用对 B 的间接引用,则可以执行接近您想要的操作。

struct B;

struct A { B *b; };
struct B : public A {};

关于c++ - 相互包含的派生和专用模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11258501/

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