26

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?

3
  • Take in a std::tuple? May 21, 2018 at 14:05
  • There's no need for tuple in this case, because all types are of the same type. I could use initializer_list, but the question is specifically about an arguments.
    – ovk
    May 21, 2018 at 14:08
  • You can still use variadic template, and than have a static assert to make sure those arguments are of the allowed types.
    – SergeyA
    May 21, 2018 at 14:10

1 Answer 1

44

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

1
  • 8
    Very elegant solution. No checks needed at all to make sure the list have the same amount of elements. +1 May 21, 2018 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.