【问题标题】:c++ issue with template class inheritance模板类继承的c ++问题
【发布时间】:2013-12-22 18:33:49
【问题描述】:

我在编译代码时遇到错误,如下所示:

#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;
};

编译器 (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

我发现如果A类不是模板类,编译不会报错。 我不明白为什么将 A 类设为模板类会导致所描述的错误。 知道原因以及如何解决问题吗?

【问题讨论】:

    标签: c++ templates inheritance


    【解决方案1】:

    没有限定 insideClass 是在第 1 阶段查找期间查找的非依赖名称。由于不知道依赖于模板参数的基类定义,因此基类中的名称将被忽略并且找不到该名称。限定条件并可能在战略位置添加 typename 应该可以解决问题(感谢 remyabel 的符号):

    typename A<T>::template insideClass<T> ic;
    

    需要template 关键字来指示即将到来的是模板,需要typename 来指示恰好是一个类型。获得从属名称应该是什么的正确拼写有时并不完全直截了当。显示问题的SSCCEhere,解决方案是here

    【讨论】:

    • typename A&lt;T&gt;::template insideClass&lt;T&gt; ic; 应该可以解决问题。
    • @remyabel:是的,这看起来不错:我在一个小型移动设备上打字,最终放弃了尝试做对;)
    【解决方案2】:

    类似这样的:

    typedef typename A<T>::template insideClass<T> ic; 
    public:
        void print(T t)
        {
            ic ic;
            ic.insideClassValue = t;
            std::cout << ic.insideClassValue << std::endl;
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多