模板的前向声明

Forward declaration of template

本文关键字:声明      更新时间:2023-10-16

我不喜欢使用前向声明作为:

struct A;
struct B
{
   A* a;
}
// Implementation

我习惯做这样的事情:

struct B
{
   struct A* a;
}

但是,当我尝试使用模板类执行此操作时,我遇到了问题:

template<typename T>
struct A
{
    struct B<T>* _t;
};
template<typename T>
struct B
{
    T _t;
};

编译器说我:

test.cpp:4:12: error: 'B' is not a template
test.cpp:8:8: error: 'B' is not a template type

我怎样才能做到这一点?

两个步骤。

步骤 1:在结构 A 之前定义结构 B

第 2 步:喜欢前向声明。

双Vigneshwaren注释与代码: 模板 结构 B { T _t; };

template<typename T>
struct A
{
    struct B<T>* _t;
};