【问题标题】:Can pure virtual function be Variadic function template? [duplicate]纯虚函数可以是可变函数模板吗? [重复]
【发布时间】:2021-06-21 05:41:32
【问题描述】:

我可以这样写一个类吗:

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

然后我想写这样的派生类:

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

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

如果这不可能,有什么方法可以实现吗?

【问题讨论】:

  • 一种可能的解决方法是为参数定义标准化结构并依赖多态性。类似this :)
  • @Fareanor 好主意,谢谢 Fareanor!

标签: c++ templates stl


【解决方案1】:

没有。虚函数根本不能是模板。这适用于任何模板(可变参数或非可变参数),以及所有虚函数——无论是否纯。

如果你仔细想想,这是有道理的。模板不是函数,它是编译器在调用它时生成函数的模板。而虚函数必须是实函数,编译器通过函数指针调用实现多态行为。

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 2018-08-05
    • 2016-02-05
    • 2019-12-14
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多