Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip some arguments in a C++ function?

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?

like image 293
kyrpav Avatar asked Sep 26 '13 09:09

kyrpav


People also ask

Can you have optional parameter in C?

Optional arguments are generally not allowed in C (but they exist in C++ and in Ocaml, etc...). The only exception is variadic functions (like printf ).

Which of the arguments can be skipped in the function call?

Default arguments can be skipped from function call​.

What is Variadic function in C?

Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.

CAN default arguments be skipped?

It's not possible to skip it, but you can pass the default argument using ReflectionFunction .


1 Answers

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.

like image 130
bstamour Avatar answered Sep 22 '22 06:09

bstamour