C++ : Instanciate template method based on overloads of another method

30 Views Asked by At

I have a method (in a class A) that has a lot of different overloads, and i am making a class B that inherits from A, changing the behavior of the method to perform a certain action before doing what it originally does. The problem is that this change has to be done on all the overloads, which can be done using a template.

class A{
  public:
  void method(int);
  void method(double);
  void method(char);
};

class B : protected A{
  public:
  template<typename T>
  void method(T t){
    A::method(t);
  }
};

In fact this actually works, but the use of a template implies putting the new code of the method in the class declaration (i.e. in the header), which is kind of messy, and i feel like there must be a way to put the code in a separate file. There is a way to do that, and it would be to just move the code of the redefined method B::method() to a separate file, and instanciate it manually for every overload. Which is pretty tedious if the number of overloads gets large, and feels pretty unnatural. So, hence my question : it there a way to directly tell the compiler to instanciate the template method B::method() for every type for which it would be valid ? (i.e. for every type A::method is overloaded for)

1

There are 1 best solutions below

0
AudioBubble On

You can use using Base::member_id; to expose members of private/protected bases:

class A{
  public:
  void method(int);
  void method(double);
  void method(char);
};

class B : protected A{
  public:
    using A::method;
};

int main() {
    B foo;

    foo.method(12);
}