简体   繁体   English

当模板和inheritance一起使用时,不知道怎么覆盖一个成员function

[英]When using template and inheritance together, I do not know how to override a member function

I have the following code that mixes template and inheritance.我有以下混合模板和 inheritance 的代码。

Class Base has some utility function to build items (the work in the sample code), and Child call the work in its implementation of the API call . Class Base有一些实用程序 function 来构建项目(示例代码中的work ),而Child在其执行 API call中调用该work

In this function在这个 function

virtual void call() override {
        Base<T>::work(); // Problem Here
        // work();
}

I try to call work() but got the following error:我尝试调用work()但收到以下错误:

test.cc: In member function ‘virtual void Child<T>::call()’:
test.cc:18:2: error: there are no arguments to ‘work’ that depend on a template parameter, so a declaration of ‘work’ must be available [-fpermissive]

So I write Base<T>::work() and makes it work.所以我写了Base<T>::work()并让它工作。

Now I have a Grandson class, who want to override the work function.现在我有一个Grandson class,他想覆盖work function。 But the override does not work as in Child<T>::call I have explicitly specified calling Base<T>::work() .但是覆盖不起作用,因为Child<T>::call我已明确指定调用Base<T>::work() So what's the correct way to implement Child<T>::call to make the override in Grandson work?那么实现Child<T>::call以使Grandson中的覆盖起作用的正确方法是什么?

#include <iostream>

template <typename T>
class Base {
protected:
    virtual void work() {
        T a;
        std::cout << "From Base" << '\n';
    }
public:
    virtual void call() = 0;
};

template <typename T>
class Child : public Base<T> {
public:
    virtual void call() override {
        Base<T>::work(); // Problem Here
        // work();
    }
};

template <typename T>
class Grandson : public Child<T> {
        protected:
                void work() override {
                        std::cout << "From Grandson" << '\n';
                }
};

int main() {
        Grandson<int> g;
        g.call();
}

Replace Base<T>::work() with this->work() .Base<T>::work()替换为this->work()


When you are a template class inheriting from a base class dependent on your template parameter, the compiler doesn't look into your base when it sees something like work() .当您是模板 class 继承自基础 class 取决于您的模板参数时,编译器在看到类似work()的内容时不会查看您的基础。 Instead, you have to tell it that it needs to do that.相反,您必须告诉它它需要这样做。 The easiest way I know of to accomplish that is to prefix the call with this-> .我所知道的最简单的方法是在调用前加上this->

As for why it does not work when you use Base<T>::work() , I am not entirely sure.至于为什么在使用Base<T>::work()时它不起作用,我不完全确定。 It's hardcoding it to call the base class implementation, but I'm fairly sure there's a similar syntax that does work.将其硬编码为调用基本 class 实现,但我相当确定有类似的语法可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM