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
}
}
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
}
}
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).