c ++嵌套模板类如何工作?

时间:2014-10-30 05:54:10

标签: c++ class templates nested

我有以下示例TestC是一个模板类。类测试使用模板类作为模板,并且有一个特殊的member_,它是嵌套的实例化A>。但是,编译器抱怨这一点。这是非法的吗?或者如何纠正它?

提前致谢

#include <iostream>
using namespace std;

template <class A>
class TestC {
    public:
    TestC(double a = 100.0) : a_(a) {};
    A member_;
    double a_;
};

template <template <class> class A>
class Test {
    public:
    Test(A<Test<A> > member = A<Test<A> >() );
    A<Test<A> > member_;
};

int main() {
    TestC< Test<TestC> > a(10.0);
    return 0;
}
  

编译错误时间:0内存:3292信号:0prog.cpp:In   'class Test'的实例化:prog.cpp:8:7:需要来自   'class TestC&gt;'prog.cpp:21:23:从这里需要   prog.cpp:16:17:错误:'Test :: member_'的类型不完整        A&gt;会员_;                    ^ prog.cpp:5:7:错误:'class TestC&gt;'类TestC {

的声明
   ^

1 个答案:

答案 0 :(得分:1)

班级

template <template <class> class A>
class Test {
    public:
    Test(A<Test<A> > member = A<Test<A> >() );
    A<Test<A> > member_;
    //^^^^^^^ this requires Test to be defined completely.
};

类似于

class Test
{
   Test member_;
};

在定义依赖于完整类定义的成员变量之前,class Test的定义尚未结束。

在常规类中,您可以使用指向该类的指针作为成员。

class Test
{
   Test* member_;
};

你可以用类模板做类似的事情。这是成功构建的程序。

#include <iostream>
using namespace std;

template <class A>
class TestC {
    public:
    TestC(double a = 100.0) : a_(a) {}
    A member_;
    double a_;
};

template <template <class> class A>
class Test {
    public:
    Test() {}
    A<Test<A>* > member_;
};

int main() {
    TestC< Test<TestC> > a;

    // type of a is TestC< Test<TestC> >
    // It has a member member_.
    // type of a.member_ is Test<TestC>
    // a.member_ has a member member_
    // type of a.member_.member_ is TestC<Test<TestC>*>
    // a.member_.member_ has a member whose type is Test<TestC>*
    // You can assign nullptr to it.
    a.member_.member_.member_ = nullptr;

    // Or you can assign to it a pointer to an object allocated from the heap.
    a.member_.member_.member_ = new Test<TestC>;

    return 0;
}