返回子类型的成员模板函数

Member template functions returning a subtype

本文关键字:函数 成员 类型 返回      更新时间:2023-10-16

有没有一种正确的方法来定义模板类的成员函数,该函数返回子类的实例?

以下是一个不在VC++2010中编译的示例:

template<class T> class A {
public:
    class B {
    public:
        T i;
    };
    A();
    B* foo();
};
/////////////////////////////////////////////
template<class T> A<T>::A() {}
template<class T> A<T>::B* A<T>::foo() {
    cout << "foo" << endl;
    return new B();
}

我得到

Error   8   error C1903: unable to recover from previous error(s); stopping compilation 

在CCD_ 1的定义开始的行。

我有iostream等的正确包含和命名空间声明。

谢谢大家!

编辑:

根据要求,以下是错误的完整列表,所有错误都在同一行:

Warning 1   warning C4346: 'A<T>::B' : dependent name is not a type
Error   2   error C2143: syntax error : missing ';' before '*'
Error   3   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error   4   error C1903: unable to recover from previous error(s); stopping compilation
Warning 5   warning C4346: 'A<T>::B' : dependent name is not a type
Error   6   error C2143: syntax error : missing ';' before '*'
Error   7   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error   8   error C1903: unable to recover from previous error(s); stopping compilation

名称A<T>::B是dependent,您需要提示编译器dependent名称是类型

template<class T> typename A<T>::B* A<T>::foo() {...}

同一行:return new B();->return new typename A<T>::B();

阅读:我必须把";模板";以及";typename";关键词?