c++named-parameters

Does C++ support named parameters?


Previously, I've worked with Python. In Python I've used named parameters (keyword argument) for function calls. The Wikipedia page about named parameters says that C++ doesn't support this feature.

Why doesn't C++ support named parameters? Will it support it in a future version of the C++ standard?


Solution

  • Does C++ support named parameters?

    No, because this feature has not been introduced to the standard. The feature didn't (and doesn't) exist in C either, which is what C++ was originally based on.

    Will it support it in a future version of the C++ standard?

    The proposal N4172: Named arguments was written for it, but has been rejected. More recently, P1229: Labelled Parameters has suggested this feature, and has not been rejected or approved yet.

    A fundamental problem in C++ is that the names of the parameters in function declarations aren't significant, and following program is well-defined:

    void foo(int x, int y);
    void foo(int y, int x);   // re-declaration of the same function
    void foo(int, int);       // parameter names are optional
    void foo(int a, int b) {} // definition of the same function
    

    If named parameters were introduced to the language, then what parameters would be passed here?

    foo(x=42, b=42);
    

    Named parameters require significantly different, and backwards incompatible system of parameter passing.


    You can emulate named parameters by using a single parameter of class type:

    struct args {
        int   a = 42;
        float b = 3.14;
    };
    
    void foo(args);
    
    // usage
    args a{};
    a.b = 10.1;
    foo(a);
    // or in C++20
    foo({.b = 10.1});