[英]Why base function cannot be accessed by derived class when involving template classes
The following code is giving compilation error: 以下代码给出了编译错误:
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();
}
ERROR 错误
Line 12: error: there are no arguments to 'bar' that depend on a template parameter, so a declaration of 'bar' must be available
Why is this error coming? 为什么会出现这个错误?
The name foo()
does not depend on any of Derived
's template parameters - it's a non-dependent name. 名称
foo()
不依赖于任何Derived
的模板参数 - 它是一个非依赖名称。 The base class where foo()
is found, on the other hand - Base<T>
- does depend on one of Derived
's template parameters (namely, T
), so it's a dependent base class . 另一方面,找到
foo()
的基类 - Base<T>
- 确实依赖于Derived
的模板参数之一(即T
),因此它是一个依赖的基类 。 C++ does not look in dependent base classes when looking up non-dependent names. 查找非依赖名称时,C ++不会查找依赖的基类。
To resolve this, you need to qualify the call to bar()
in Derived::foo()
as either this->bar()
or Base<T>::bar()
. 要解决此问题,您需要将对
Derived::foo()
bar()
的调用限定为this->bar()
或Base<T>::bar()
。
This C++ FAQ item explains it nicely: see http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19 这个C ++ FAQ项很好地解释了它:请参阅http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19
The code you've provided doesn't have a build error on the line you indicate. 您提供的代码在您指定的行上没有构建错误。 It DOES have one here:
它有一个在这里:
Derived *b = new Derived;
which should read: 应该是:
Derived<int> *b = new Derived<int>();
(or use whatever type you want instead of int.) (或使用你想要的任何类型而不是int。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.