小编ham*_*zzi的帖子

如何在可变参数派生类中执行 crtp 基类的所有函数?

我有一个CRTP派生类,它是它可以继承的所有 CRTP 基类的可变模板。我想在派生类的方法(printAll 函数)中执行每个继承类的函数(在本例中为 print 函数)。我怎样才能做到这一点?

// Base Class 1
template<typename Derived>
struct Mult
{
  void print()
  {
    int a = (static_cast<Derived const&>(*this)).m_a;
    int b = (static_cast<Derived const&>(*this)).m_b;
    std::cout << "a * b: " << a * b << "\n";
  }
};

// Base Class 2
template<typename Derived>
struct Add
{
  void print()
  {
    int a = (static_cast<Derived const&>(*this)).m_a;
    int b = (static_cast<Derived const&>(*this)).m_b;
    std::cout << "a + b: " << a + b << "\n";
  }
}; …
Run Code Online (Sandbox Code Playgroud)

c++ crtp variadic-templates c++17

3
推荐指数
1
解决办法
112
查看次数

标签 统计

c++ ×1

c++17 ×1

crtp ×1

variadic-templates ×1