Skip some arguments in a C++ function?

kyrpav picture kyrpav · Sep 26, 2013 · Viewed 18.9k times · Source

I have a C++ function that has 5 arguments, all of which have default values. If I pass in the first three arguments, the program will assign a default value to the last two arguments. Is there any way to pass 3 arguments, and skip one in the middle, giving values to say, the first, second, and fifth arguments?

Answer

bstamour picture bstamour · Sep 26, 2013

Not directly, but you might be able to do something with std::bind:

int func(int arg1 = 0, int arg2 = 0, int arg3 = 0);

// elsewhere...
using std::bind;
using std::placeholders::_1;
auto f = bind(func, 0, _1, 0);

int result = f(3); // Call func(0, 3, 0);

The downside is of course that you are re-specifying the default parameters. I'm sure somebody else will come along with a more clever solution, but this could work if you're really desperate.