Search code examples
c++metaprogrammingc++20template-meta-programming

Expand constexpr array into positional function arguments


I'm used to using x macros to have powerful code generation. One of the features I like specifically is that I can't mess up the order of the values nor can I forget one.

I want to know if there's a similar strategy for arrays and function params

For example:

If a library provides a function:

void foobar(std::string_view k, std::string_view l, std::string_view m);

and in my code base I have:

constexpr std::array<std::string_view, 3> kConstants{"one", "two", "three"};

Is there some expansion magic I can do to get something like:

foobar(kConstants);

Note for this to be useful to me I must do this without modifying foobar. I know I can do something like this with x macros.


Solution

  • You're looking for std::apply:

    std::apply(foobar, kConstants);