Suppose there is a function with the following prototype:
void fun (int = 10, int = 20, int = 30, int = 40);
If this function is called by passing 2 arguments to it, how can we make sure that these arguments are treated as first and third, whereas, the second and the fourth are taken as defaults.
// three and four argument version
void fun (int a, int b, int c, int d = 40)
{
...
}
// two argument version
void fun (int a, int c)
{
fun(a, 20, c, 40);
}
// one and zero argument version
void fun(int a = 10)
{
fun(a, 20, 30, 40);
}
But really my advice would be don't.
You can define the Args
structure like:
struct Args {
int a = 10;
int b = 20;
int c = 30;
int d = 40;
};
and then you would have the following:
void fun(Args);
fun({.a=60, .c=70}); // a=60, b=20, c=70, d=40
Besides this approach, you can use NamedType
library that implements named arguments in C++. For more usage info, check here.
UPDATE
Designated initializers feature is available by GCC and CLANG extensions and, from C++20, it is available by C++ standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With