如何以相同的方法在子类中超载的相同方法来实现工作变量参数方法

How to make working variadic arguments method inheritance with same method overloaded on child class

本文关键字:方法 实现 工作 参数 变量 超载 子类 中超      更新时间:2023-10-16

以下代码工作:

class Test_Interface {
public:
    template<typename... Args>
    void Split(int weight, Args... args){
        Split(weight);
        Split(args...);
    }
    virtual void Split(int weight) {
        std::cout << "Test_Interface::Split weight: " << weight << std::endl;
    };
};
class Test : public Test_Interface {};
int main()
{
    Test test;
    test.Split(1, 20, 300);
}

但是,如果我定义了 split in test 类中的超载,则如下:

class Test : public Test_Interface {
public:
    virtual void Split(int weight) {
        std::cout << "Test::Split weight: " << weight << std::endl;
    };
};

然后我会收到错误:错误:呼叫'test :: split(int,int,int)'

没有匹配函数

我知道,如果我还定义了类 test test 中的variadic参数方法:

class Test : public Test_Interface {
public:
    template<typename... Args>
    void Split(int weight, Args... args){
        Split(weight);
        Split(args...);
    }
    virtual void Split(int weight) {
        std::cout << "Test::Split weight: " << weight << std::endl;
    };
};

它再次工作,但它不做一开始就打算做的事情,它只有一个位置(界面),其中定义的variadic参数方法,并且只有每个派生的类仅使用非variadic方法的自定义实现。我的目标是避免一遍又一遍地复制相同的代码,并在多个位置维护。为什么当儿童课不超载方法后,该方法继承起作用?有没有办法在不复制的情况下进行操作?谢谢

当您声明Test::Split函数时,您 hide 继承的函数。之后,当您在Test对象上使用Split时,编译器只知道Test::Split而不是父母Test_Interface::Split功能。

解决方案很容易:您将符号从父级将符号拉入Test类:

class Test : public Test_Interface {
public:
    using Test_Interface::Split;  // Pull in the Split symbol from the parent class
    virtual void Split(int weight) {
        std::cout << "Test::Split weight: " << weight << std::endl;
    };
};