ovk
ovk

Reputation: 2358

Is it possible to expand non-variadic arguments in a variadic template function?

It is probably easier to explain what I mean by an example. Imagine a following template:

template <class... Args>
std::tuple<Args...> foo();

It can be invoked, for example, like this:

auto ret = foo<int, bool>();

But what if I want to pass additional arguments to the function, based on the number of variadic template arguments? For example, let's say I want to pass a character string literal for every Args:

auto ret = foo<int, bool>("a", "b");

The problem with this, is that it does not seem possible to expand non-variadic arguments, so the following obviously doesn't compile:

template <class... Args>
std::tuple<Args...> foo(const char*... names);

Is there any sensible way to implement this?

Upvotes: 27

Views: 1336

Answers (1)

Dan M.
Dan M.

Reputation: 4052

You can do this with something like

template <class... Args>
std::tuple<Args...> foo(proxy<Args, const char*>... names);

where proxy is

template<class T, class E>
using proxy = E;

You can see this in action here: https://godbolt.org/g/SHBYzy

Upvotes: 46

Related Questions