简体   繁体   English

为什么在涉及模板类时,派生类无法访问基函数

[英]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.

相关问题 为什么不能使用派生类代替基类作为模板参数? - Why derived class cannot be used in place of base class, as a template parameter? 为什么派生类指针不能分配给基类的指针? - Why derived class pointer cannot be assigned a base classes' pointer? 派生类在基类中调用模板函数时的链接问题 - Linking problem when derived class calls a template function in base class 检查基类中派生的模板类是否相等 - Check for equality of derived template classes in the base class 为什么使用基类指针来派生类 - Why use base class pointers for derived classes 通过模板类的派生类的函数进行递归 - recursion through a function of derived classes of a template class C ++:“专门化”一个成员函数模板,用于处理来自某个基类的派生类 - C++: “specializing” a member function template to work for derived classes from a certain base class 为什么派生类中的模板名称可用(基类是模板的实例)? - Why is template name available in derived class (the base class is an instance of the template)? 模板类和派生类 - Template class and derived classes C++:为什么在派生的 Class 中无法访问受保护的构造函数? - C++: Why Protected Constructor Cannot be Accessed in the Derived Class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM