gpt4 book ai didi

c++ - 如何在可变派生类中执行来自 crtp 基类的所有函数?

转载 作者:搜寻专家 更新时间:2023-10-31 00:07:13 27 4
gpt4 key购买 nike

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

最佳答案

您可以使用 fold expression ,C++17 中的新语言特性之一:

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

关于c++ - 如何在可变派生类中执行来自 crtp 基类的所有函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54617841/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com