1

What would be equal of Java function with any number of parameters in C++?

void anyNumberOfParamas(String... strings) {
    for (String str : strings) {
        // do something with string
    }
}
user924
  • 8,146
  • 7
  • 57
  • 139
  • https://stackoverflow.com/questions/1579719/variable-number-of-parameters-in-function-in-c possible duplicate. ... exists in c, too. – Gladaed Mar 13 '18 at 13:46
  • 2
    [Variadic functions](http://en.cppreference.com/w/cpp/utility/variadic), and since C++11 [variadic templates](https://en.wikipedia.org/wiki/Variadic_template), more general and powerful. – jdehesa Mar 13 '18 at 13:48

1 Answers1

4

You have two choices: a variadic template or a function taking std::initializer_list.


The first one looks like this:

template <typename... Ts>
void anyNumberOfParams(const Ts&... xs)
{
    (something(xs), ...);
}

With this approach, you get a different instantiation of anyNumberOfParams each you time you call it with different types. The "iteration" is done at compile-time.

You also need to constrain Ts... properly if you want to allow this function to only accept std::string.


The second one looks like this:

void anyNumberOfParams(std::initializer_list<std::string> xs)
{
    for(const auto& x : xs) something(x);
}

std::initializer_list is basically syntactic sugar over a const array of elements. In this case, the iteration is done at run-time and there is only a single instantiation of anyNumberOfParams.

Unfortunately, std::initializer_list has quirks you should be aware of (e.g. cannot move elements from it).

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416