27

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? Commented 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. Commented 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. Commented May 21, 2018 at 14:10

1 Answer 1

46

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

Sign up to request clarification or add additional context in comments.

1 Comment

Very elegant solution. No checks needed at all to make sure the list have the same amount of elements. +1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.