quot;not declared in this scopequot; error with templates and inheritance(“未在此范围内声明模板和继承错误)
问题描述
这是重现我的问题的代码示例:
Here is code sample which reproduces my problem:
template <typename myType>
class Base {
public:
Base() {}
virtual ~Base() {}
protected:
int myOption;
virtual void set() = 0;
};
template <typename InterfaceType>
class ChildClass : public Base < std::vector<InterfaceType> >
{
public:
ChildClass() {}
virtual ~ChildClass() {}
protected:
virtual void set();
};
template <typename InterfaceType>
void ChildClass<InterfaceType>::set()
{
myOption = 10;
}
我在main()
中的用法:
ChildClass<int> myObject;
我收到以下错误(ubuntu 上的 gcc 4.4.3):
I get the following error (gcc 4.4.3 on ubuntu):
'myOption' 未在此范围内声明
‘myOption’ was not declared in this scope
如果我的 ChildClass 没有新的模板参数,这可以正常工作,即:
If my ChildClass would be without new template parameter this would work fine, i.e.:
class ChildClass : public Base < std::vector<SomeConcreteType> >
<小时>
编辑
我已经设法解决它,如果我的 set 方法看起来像:
Edit
I've managed to solve it, if my set method looks like:
Base<std::vector<InterfaceType> >::myOption = 10;
它工作正常.仍然不确定为什么我需要指定所有模板参数.
It works fine. Still though not sure why I need to specify all template parameters.
推荐答案
myOption
不是依赖名称,即它不显式依赖模板参数,因此编译器会尝试查找它早期的.您必须将其设为依赖名称:
myOption
is not a dependent name, i.e. it doesn't depend on the template arguments explicitly so the compiler tries to look it up early. You must make it a dependent name:
template <typename InterfaceType>
void ChildClass<InterfaceType>::set()
{
this->myOption = 10;
}
现在它取决于 this
的类型,因此取决于模板参数.因此编译器会在实例化时绑定它.
Now it depends on the type of this
and thus on the template arguments. Therefore the compiler will bind it at the time of instantiation.
这称为两阶段名称查找.
这篇关于“未在此范围内声明"模板和继承错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“未在此范围内声明"模板和继承错误


基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01