“未在此范围内声明"模板和继承错误
这是重现我的问题的代码示例:
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.
这称为两阶段名称查找.
相关文章