如何使用在子 class 上重载的相同方法使工作的可变参数方法继承

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

以下代码有效:

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);
}

但是如果我在 Test class 中为方法 Split 定义重载,例如:

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

然后我得到如下错误:错误:没有匹配函数调用 'Test::Split(int, int, int)'

我知道如果我也在 class Test 中定义可变参数方法,例如:

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;
    };
};

它又能工作了,但它并没有做最初的预期,它只有一个地方(接口)定义了可变参数方法,并且每个派生的 class 仅具有自定义非可变方法的实现。我的目标是避免一遍又一遍地复制粘贴相同的代码并将其维护在多个地方。为什么当 child class 不重载方法继承工作?有没有不用复制粘贴的方法?谢谢

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

解决方案非常简单:将父项 class 中的符号拉入 Test class:

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;
    };
};