2

Can i write a class like this:

class Base {
  template <typename...Args>
  virtual double calculate(const Args&...args) = 0;
};

then i want to write derived class like this:

class Derived1 : public Base {
  double calculate(int a) {
  }
};

class Derived2 : public Base {
  double calculate(int a, int c) {
  }
};

if this is not possible, is there any methods can achieve this?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
nick
  • 832
  • 3
  • 12
  • 1
    A possible workaround would be to define a standardized structure for the parameters and rely on polymorphism. Something like [this](https://godbolt.org/z/xofTK9a1P) :) – Fareanor Mar 24 '21 at 14:30
  • @Fareanor good idea, thanks Fareanor! – nick Mar 25 '21 at 02:37

1 Answers1

5

No. Virtual functions can not be templates at all. That applies to any template (variadic or not), and all virtual functions - pure or not.

If you think about it, it makes sense. Template is not a function, it is a template by which compiler will make a function when it is called. A virtual function, on the other hand, have to be a real function, which compiler calls through function pointer to achieve polymorphic behavior.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
SergeyA
  • 61,605
  • 5
  • 78
  • 137