我有一个必须使用许多不同类型调用的重载函数。简单的方法是:

uint8_t a;
uint16_t b;
//....
double x;

doSomething(a);
doSomething(b);
//...
doSomething(x);

可以使用可变参数模板来简洁地表达这些调用,如Q&A所述。该代码将如下所示:
auto doSomethingForAllTypes = [](auto&&... args) {
    (doSomething(args), ...);
};

uint8_t a;
uint16_t b;
//....
double x;

doSomethingForAllTypes(a, b, ... ,x);

但是我必须在代码中的许多地方执行此操作,因此我只想定义一次类型列表。我希望代码在概念上看起来像这样:
auto doSomethingForAllTypes = [](auto&&... args) {
    (doSomething(args), ...);
};

someContainer allTypesNeeded(uint8_t, uint16_t, ... double);

doSomethingForAllTypes(allTypesNeeded);

怎么办呢?

最佳答案

使用std::tuplestd::apply

std::tuple<uint8_t, uint16_t, double> tup{};
std::apply([](const auto&... arg) { (doSomething(arg), ...); }, tup);

关于具有许多不同类型的C++调用函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56000650/

10-11 23:01
查看更多