【问题标题】:How to execute all functions from crtp base classes in a variadic derived class?如何在可变参数派生类中执行 crtp 基类的所有函数?
【发布时间】:2019-02-10 15:17:35
【问题描述】:

我有一个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";
  }
};

template<template<typename> typename... Bases>
struct Derived : public Bases<Derived<Bases...>>...
{
  int m_a, m_b;
  Derived(int a, int b) : m_a(a), m_b(b) {}
  void printAll()
  {
    // Should execute the print method of all the derived classes
    this->print();
  }
};


int main()
{
  Derived<Mult, Add> d(2, 3);
  // should print:
  // a + b: 5
  // a * b: 6
  d.printAll();
}

【问题讨论】:

  • Mult 不是类模板,不能作为Derived 的参数。它还使用未定义的名称Derived
  • 感谢提示,已编辑完毕

标签: c++ c++17 variadic-templates crtp


【解决方案1】:

您可以使用fold expression,这是 C++17 中的新语言功能之一:

void printAll()
{
    (Bases<Derived>::print(), ...);
}

【讨论】:

    【解决方案2】:
      void printAll()
      {
        auto _ = {(Bases<Derived<Bases...>>::print(), 0) ...};
      }
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 2013-11-30
      相关资源
      最近更新 更多