模板类继承的 C++ 问题
c++ issue with template class inheritance
我在编译代码时遇到错误,可以按如下方式琐碎:
#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;
};
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题