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.
这称为两阶段名称查找.
这篇关于“未在此范围内声明"模板和继承错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“未在此范围内声明"模板和继承错误


基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01