Is there named parameters in modern C++?

283 Views Asked by At

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.

1

There are 1 best solutions below

0
Ted Lyngmo On BEST ANSWER

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.