C++ 模板和继承的“未在此范围内声明”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7076169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"not declared in this scope" error with templates and inheritance
提问by Tadzys
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;
}
My usage in main()
:
我的用法main()
:
ChildClass<int> myObject;
I get the following error (gcc 4.4.3 on ubuntu):
我收到以下错误(ubuntu 上的 gcc 4.4.3):
‘myOption' was not declared in this scope
“myOption”未在此范围内声明
If my ChildClass would be without new template parameter this would work fine, i.e.:
如果我的 ChildClass 没有新的模板参数,这将正常工作,即:
class ChildClass : public Base < std::vector<SomeConcreteType> >
Edit
编辑
I've managed to solve it, if my set method looks like:
如果我的 set 方法看起来像:
Base<std::vector<InterfaceType> >::myOption = 10;
It works fine. Still though not sure why I need to specify all template parameters.
它工作正常。仍然不确定为什么我需要指定所有模板参数。
回答by ybungalobill
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:
myOption
不是依赖名称,即它不显式依赖模板参数,因此编译器会尝试尽早查找它。您必须使其成为依赖名称:
template <typename InterfaceType>
void ChildClass<InterfaceType>::set()
{
this->myOption = 10;
}
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.
现在它取决于类型,this
因此取决于模板参数。因此编译器将在实例化时绑定它。
This is called Two-phase name lookup.
这称为两阶段名称查找。
回答by Eric Z
C++03 14.6.2 Dependent names
C++03 14.6.2 从属名称
In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examinedduring unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.
在类模板或类模板的成员的定义中,如果类模板的基类依赖于模板参数,则在类定义点的非限定名称查找期间不会检查基类范围模板或成员或在类模板或成员的实例化期间。
The following code should work.
以下代码应该可以工作。
template <typename InterfaceType>
void ChildClass<InterfaceType>::set()
{
Base<std::vector<InterfaceType> >::myOption = 10;
}