“未在此范围中声明”模板和继承的错误 [英] "not declared in this scope" error with templates and inheritance

查看:685
本文介绍了“未在此范围中声明”模板和继承的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码示例再现了我的问题:

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> >






编辑



我设法解决它,如果我的设置方法看起来像:


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;
}

现在取决于 code>,因此取决于模板参数。因此,编译器将在实例化时绑定它。

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.

这称为两阶段名称查找

这篇关于“未在此范围中声明”模板和继承的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆