Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to ensure two arguments passed to a function are treated as the first and third argument in C++?

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.

like image 592
Abhimanyu Solanki Avatar asked Dec 18 '22 13:12

Abhimanyu Solanki


2 Answers

// 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.

like image 173
john Avatar answered May 18 '23 12:05

john


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.

like image 37
NutCracker Avatar answered May 18 '23 12:05

NutCracker