简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM