How can I write a function that accepts a variable number of arguments? Is this possible, how?
We could also use an initializer_list if all arguments are const and of the same type
C-style variadic functions are supported in C++.
However, most C++ libraries use an alternative idiom e.g. whereas the 'c' printf
function takes variable arguments the c++ cout
object uses <<
overloading which addresses type safety and ADTs (perhaps at the cost of implementation simplicity).
Apart from varargs or overloading, you could consider to aggregate your arguments in a std::vector or other containers (std::map for example). Something like this:
template <typename T> void f(std::vector<T> const&);
std::vector<int> my_args;
my_args.push_back(1);
my_args.push_back(2);
f(my_args);
In this way you would gain type safety and the logical meaning of these variadic arguments would be apparent.
Surely this approach can have performance issues but you should not worry about them unless you are sure that you cannot pay the price. It is a sort of a a "Pythonic" approach to c++ ...
Using variadic templates, example to reproduce console.log
as seen in JavaScript:
Console console;
console.log("bunch", "of", "arguments");
console.warn("or some numbers:", 1, 2, 3);
console.error("just a prank", "bro");
Filename e.g. js_console.h
:
#include <iostream>
#include <utility>
class Console {
protected:
template <typename T>
void log_argument(T t) {
std::cout << t << " ";
}
public:
template <typename... Args>
void log(Args&&... args) {
int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
cout << endl;
}
template <typename... Args>
void warn(Args&&... args) {
cout << "WARNING: ";
int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
cout << endl;
}
template <typename... Args>
void error(Args&&... args) {
cout << "ERROR: ";
int dummy[] = { 0, ((void) log_argument(std::forward<Args>(args)),0)... };
cout << endl;
}
};
As others have said, C-style varargs. But you can also do something similar with default arguments.