模板类继承的c ++问题

use*_*609 5 c++ inheritance templates

我在编译可以轻视的代码时遇到错误,如下所示:

#include<iostream>

template <class T>
class A
{
    protected:
        T protectedValue;

        template<class TT>
        class insideClass
        {
            public:
                TT insideClassValue;
        };
};

template<class T>
class B : public A<T>
{
    public:
        void print(T t)
        {
            insideClass<T> ic;    // <-- the problem should be here
            ic.insideClassValue = t;
            std::cout << ic.indideClassValue << std::endl;
        };
};

int main()
{
    double v = 2.;
    B<double> b;
    b.print(v);

    return 0;
};
Run Code Online (Sandbox Code Playgroud)

编译器(g ++)给出以下错误:

main.C: In member function ‘void B<T>::printA()’:
main.C:23:4: error: ‘insideClass’ was not declared in this scope
main.C:23:17: error: expected primary-expression before ‘>’ token
main.C:23:19: error: ‘ic’ was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

我发现如果A类不是模板类,编译不会给出任何错误.我不明白为什么将类A作为模板类会导致所描述的错误.有关原因以及如何解决问题的任何想法?

Die*_*ühl 5

没有资格insideClass是一个非依赖名称,在第1阶段查找期间查找.由于根据模板参数定义基数是未知的,因此将忽略基类中的名称并找不到名称.资格和可能typename在战略位置添加应解决问题(感谢remyabel的符号):

typename A<T>::template insideClass<T> ic;
Run Code Online (Sandbox Code Playgroud)

template需要使用关键字来指示即将发生的是模板,并且typename需要指示恰好是类型.获取依赖名称的正确拼写有时并不完全是直截了当的.显示问题的SSCCE在这里,解决方案就在这里.

  • `typename A <T> :: template insideClass <T> ic;`应该做的伎俩. (3认同)