假设我有以下类层次结构:
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 吐出以下内容:
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 派生,则此代码段编译得很好,因此问题显然与编译时未知的基类类型有关。但是自从我没有在任何地方实例化任何一个类的对象,我不明白为什么这很重要。
基本上,如果不求助于 -fpermissive
,我将如何解决错误? ?
最佳答案
非依赖名称(即不依赖于模板参数的名称)在解析模板时查找,而不是在实例化模板时查找。您需要使 do_foo
成为从属名称。基本上有两种方法可以实现这一点:
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;
}
};
关于c++ - 在模板虚类层次结构中调用基类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14318958/