【问题标题】:Member template functions returning a subtype返回子类型的成员模板函数
【发布时间】:2012-07-10 13:41: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 

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

【问题讨论】:

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


【解决方案1】:

名称A&lt;T&gt;::B是依赖的,你需要提示编译器依赖的名称是类型

template&lt;class T&gt; typename A&lt;T&gt;::B* A&lt;T&gt;::foo() {...}

这一行相同:return new B(); -> return new typename A&lt;T&gt;::B();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    相关资源
    最近更新 更多