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.
nosid Apr 6 2018-12-12T00: 00Z
source share