我在编译一段可以简单化如下的代码时遇到错误:
#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
我想通了,如果class A不是模板类,编译是不会报错的。 我不明白为什么将类 A 设为模板类会导致所描述的错误。 关于原因以及如何解决问题的任何想法?
最佳答案
没有限定 insideClass
是一个非依赖名称,在阶段 1 查找期间查找。由于依赖于模板参数的基类定义未知,因此忽略基类中的名称并且找不到该名称。限定并可能在战略位置添加 typename
应该可以解决问题(感谢 remyabel 的符号):
typename A<T>::template insideClass<T> ic;
需要 template
关键字来指示即将到来的是一个模板,并且需要 typename
来指示它恰好是一个类型。获得从属名称的正确拼写有时并不完全直接。 SSCCE显示问题是 here解决方案是here .
关于c++ 模板类继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20732666/