Search code examples
c++functionargumentsparameter-passing

Is there a way in C++ to pass arguments by name like in python?


Is there a way in C++ to pass arguments by name like in python? For example I have a function:

void foo(int a, int b = 1, int c = 3, int d = 5);

Can I somehow call it like:

foo(5 /* a */, c = 5, d = 8);

Or

foo(5, /* a */, d = 1);

Solution

  • There are no named function parameters in C++, but you can achieve a similar effect with designated initializers from C++20.

    Take all the function parameters and put them into a struct:

    struct S 
    {
        int a{}, b{}, c{}, d{};
    };
    

    Now modify your function to take an instance of that struct (by const& for efficiency)

    void foo(S s) 
    {
        std::cout << s.a << " " << s.b << " " << s.c << " " << s.d;  // for example
    }
    

    and now you can call the function like this:

    foo({.a = 2, .c = 3});  // prints 2 0 3 0 
                            // b and d get default values of 0
    

    Here's a demo