2

Following code works:

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

But if I define overload for method Split in Test class like:

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

Then I get error like: error: no matching function for call to 'Test::Split(int, int, int)'

I know that if I also define variadic arguments method in class Test like:

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

It work again but then it doesn't do what was intendend in the first place, which is having only one place (interface) where is defined variadic arguments method and having each derived class only with custom implementation of non-variadic method. My goal is to avoid copy-pasting same code over and over again and maintain it on multiple places. Why when child class do not overload the method inheritance work ? Is there a way to do it without copy-pasting ? Thank you

Kazz
  • 1,030
  • 8
  • 16

1 Answers1

4

When you declare the Test::Split function, you hide the inherited functions. After that, when you use Split on a Test object, then the compiler only knows about Test::Split and not the parents Test_Interface::Split functions.

The solution is quite easy: You pull in the symbols from the parent class into the 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;
    };
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621