![](/img/trans.png)
[英]Why derived class cannot be used in place of base class, as a template parameter?
[英]Why base function cannot be accessed by derived class when involving template classes
以下代码给出了编译错误:
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();
}
错误
Line 12: error: there are no arguments to 'bar' that depend on a template parameter, so a declaration of 'bar' must be available
为什么会出现这个错误?
名称foo()
不依赖于任何Derived
的模板参数 - 它是一个非依赖名称。 另一方面,找到foo()
的基类 - Base<T>
- 确实依赖于Derived
的模板参数之一(即T
),因此它是一个依赖的基类 。 查找非依赖名称时,C ++不会查找依赖的基类。
要解决此问题,您需要将对Derived::foo()
bar()
的调用限定为this->bar()
或Base<T>::bar()
。
这个C ++ FAQ项很好地解释了它:请参阅http://www.parashift.com/c++-faq-lite/templates.html#faq-35.19
您提供的代码在您指定的行上没有构建错误。 它有一个在这里:
Derived *b = new Derived;
应该是:
Derived<int> *b = new Derived<int>();
(或使用你想要的任何类型而不是int。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.