Function with a variable number of arguments with known types, C ++ 11 path

I already know the way stdarg.h has a function with variable arguments in C ++, as discussed here . I also know that the C ++ 11 standard has variable templates, as described here .

But in both of the above schemes, we do not know (and cannot force) argument types at compile time afaik. I am looking to pass variable arguments to known types for a function. I think this can be done because I read about it here :

Variadic templates, which can also be used to create functions that accept a variable number of arguments, are often the best choice because they do not impose restrictions on the types of arguments, do not perform integral and floating stocks, and are type safe.

Is it possible? If so, how can I do this?

+19
c ++ c ++ 11 templates variadic-functions variadic-templates
Apr 6 2018-12-12T00:
source share
2 answers

Directly write a function with variation patterns that take an arbitrary number of arguments. The only difference from the general template is that the specific type is used as the first argument (head) - instead of the template parameter. The following example shows the foobar function, which accepts an arbitrary number of lines.

 // used for end of recursion - and for the empty arguments list void foobar() { } template <typename ...Tail> void foobar(const std::string& head, Tail&&... tail) { // do something with head std::cout << head << '\n'; // call foobar recursively with remaining arguments foobar(std::forward<Tail>(tail)...); } foobar("Hello", "World", "..."); 

Personally, I prefer to use std::initializer_list instead of variable templates. Since variable templates are more complex and require additional experience. Using std::initializer_list it might look like this:

 void foobar(std::initializer_list<std::string> values) { for (auto& value : values) { // do something with value std::cout << value << '\n'; } } foobar({ "Hello", "World", "...", }); 

Unfortunately, extra curly braces are required when using std::initializer_list with regular functions. They are not required for constructors if the new initializer syntax is used.

Edit: Rewrote the answer according to the reviews. In particular, I reordered the two solutions / examples.

+30
Apr 6 2018-12-12T00:
source share

If the variable parameters are all of the same type, you can change the function signature to take an array of these types instead of using "...".

+2
Apr 6 2018-12-12T00:
source share



All Articles