Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there named parameters in modern C++? [duplicate]

In some languages like C# and Python there is a notion of 'named parameters'. In a book on C# I have found the code:

static void print_nums(int x = 0, int y = 0, int z = 0)
{
    Console.WriteLine(x, y, z);
}

And then one can invoke the function like this

print_nums(y: 3);

Is there something like that in C++? I've seen some questions like this, but they about 7-8 years old, so maybe in newer versions of C++ the syntax was added? I've also seen that this type of functionality can be implemented by hand, but my question is about standard.

like image 519
ProMike Avatar asked Oct 30 '25 02:10

ProMike


1 Answers

Sort of. Since C++20, you can use designated initializers to a similar effect:

struct params {
    int x;
    int y;
    int z;
};

void func(params p) {
}

int main() {
    func({.y = 3});                   // p.x and p.z will be 0, p.y = 3
    func({.x = 3, .y = 10, .z = 2});  // here all are initialized to resp. Value
}

Note that you need to name the designated members in the order they appear in params.

like image 51
Ted Lyngmo Avatar answered Oct 31 '25 15:10

Ted Lyngmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!