以下代码给出了编译错误:
template <typename T>
class Base
{
public:
void bar(){};
};
template <typename T>
class Derived : public Base<T>
{
public:
void foo() { bar(); } //Error
};
int main()
{
Derived *b = new Derived;
b->foo();
}
Run Code Online (Sandbox Code Playgroud)
错误
Line 12: error: there are no arguments to 'bar' that depend on a template parameter, so a declaration of 'bar' must be available
为什么会出现这个错误?
HC4*_*ica 14
该名称foo()不依赖于任何Derived模板参数 - 它是一个非依赖名称.foo()另一方面,找到的基类Base<T>- 确实取决于其中一个Derived模板参数(即,T),因此它是一个从属基类.查找非依赖名称时,C++不会查找依赖的基类.
为了解决这个问题,就需要调用资格bar()在Derived::foo()为任一this->bar()或Base<T>::bar().
这个C++ FAQ项很好地解释了它:请参阅http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19