模板类继承的 C++ 问题

c++ issue with template class inheritance

本文关键字:C++ 问题 继承      更新时间:2023-10-16

我在编译代码时遇到错误,可以按如下方式琐碎:

#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 作为模板类会导致所描述的错误。对原因以及如何解决问题的任何想法?

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

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

需要 template 关键字来指示即将推出的是模板,需要typename来指示它恰好是一种类型。获得从属名称的正确拼写有时并不完全简单。显示问题的SSCCE在这里,解决方案在这里。

像这样:

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