Search code examples
c++templatescontainersvariadic

C++ call function with many different types


I have an overloaded function that I have to call with many different types. The simple approach is:

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

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

expressing those calls succinctly can be done with a variadic template as explained at this Q&A. The code will look somewhat like this:

auto doSomethingForAllTypes = [](auto&&... args) {
    (doSomething(args), ...);
};

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

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

But I'll have to do this at many places in the code, so I'd like to define the list of types only once. I'd like to have code that looks conceptually like this:

auto doSomethingForAllTypes = [](auto&&... args) {
    (doSomething(args), ...);
};

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

doSomethingForAllTypes(allTypesNeeded);

How could this be done?


Solution

  • With std::tuple and std::apply

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