在模板虚拟类层次结构中调用基类方法 [英] Calling a base class method in a template virtual class hierarchy

查看:140
本文介绍了在模板虚拟类层次结构中调用基类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下类层次结构:

Let's say I have the following class hierarchy:

template< class T >
class TestBase {

public:

    virtual T const & do_foo() = 0;

};

template< class T >
class TestDerived : public virtual TestBase< T > {

public:

    virtual int do_bar() {
        return do_foo() + 1;
    }

};

GCC会输出以下内容:

GCC spits out the following:

error: there are no arguments to ‘do_foo’ that depend on a template parameter, so a declaration of ‘do_foo’ must be available [-fpermissive]
note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)

现在,如果我改变这个从一个已知类型(例如 class TestDerived:public virtual TestBase< int> )实例化的TestBase派生,该代码片段编译正好,所以问题显然与在编译时未知的基类类型有关,但由于我没有实例化任何类的对象,我不明白为什么这应该是重要的。

Now, if I change this to derive from a TestBase instantiated from a known type (e.g. class TestDerived : public virtual TestBase< int >, this snippet compiles just fine so the problem apparently has to do with the base class type being unknown at compile time. But since I haven't instantiated objects of either class anywhere, I don't see why this should even matter.

基本上,我如何解决这个错误,而不诉诸 -fpermissive

Basically, how would I resolve the error without resorting to -fpermissive?

推荐答案

解析模板时,现在在实例化模板时,将查找非依赖名称(即不依赖于模板参数的名称)。您需要使 do_foo 一个依赖名称。基本上有两种方法来实现这一点:

Non-dependent names (that is, names which do not depend on template arguments), are looked up when parsing the template, now when instantiating it. You need to make do_foo a dependent name. There are basically two ways to achieve this:

virtual int do_bar() {
    return this->do_foo() + 1;
}

template< class T >
class TestDerived : public virtual TestBase< T > {

public:
    using TestBase<T>::do_foo;

    virtual int do_bar() {
        return do_foo() + 1;
    }

};

这篇关于在模板虚拟类层次结构中调用基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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