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

标签 c++ visual-studio-2010 templates visual-c++

是否有正确的方法为模板类定义成员函数,返回子类的实例?

这是一个无法在 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 

foo定义开始的行。

我对 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是相关的,您需要提示编译器相关名称是类型

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

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

阅读:Where and why do I have to put the "template" and "typename" keywords?

关于c++ - 返回子类型的成员模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11414610/

相关文章:

c++ - 尝试编译包含 Root (Cern) 参数的 C++ 代码

C++ 继承 : Destructor does not get called

vb.net - 在 Visual Studio 2010 中获取最佳分辨率

c++ - 模板<class T, int N> void h(T const(&)[N]);作为 friend 功能

c++ - 将模板类型参数作为模板非类型参数的类型传递

javascript - 是否有用于 Ken Burns 效果的 JQuery 插件?

c++ - 随机 std::array

c++ - 什么时候不能将对象转换为引用?

c++:初始化结构的正确方法

visual-studio-2010 - Visual Studio 数据库项目和 aspnet_regsql.exe