You can do the following, which supports default values to a limited amount (limited by the template system of C++). You will need to compile this with the newest standard (C++11)
// used to skip arguments and default to the previously specified value
struct UseDefault {
// empty intentionally!
};
// using this is optional, and only required if you want to provide default values by the CALLED function
template <typename T, T def> struct Default {
T value;
operator T() {
return value;
}
Default(T value) : value(value) {}
Default(UseDefault ignore) : value(def) {(void)ignore;}
};
// using tuple, you can bundle any number of parameters to one
int myFunc(std::tuple<Default<int,7>,Default<char,'x'>,std::string> parameters) {
std::cout << std::get<0>(parameters) << ", " << std::get<1>(parameters) << std::endl;
return 0;
}
You can then invoke myFunc
like this:
func(std::make_tuple(6,UseDefault(),"hi"));
Note however, that there are some limitation to the template parameter types, for instance, you cannot pass strings (or char*
s for that matter) as template parameters. However, if you only need reasonable basic default values, this could work.
Of course if you drop your requirement to specify default values, you can simply use the std::tuple
without my Default
type.