在 C++ 中有没有办法像在 python 中那样按名称传递参数?

2022-01-21 00:00:00 function parameter-passing arguments c++

在 C++ 中有没有办法像在 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);

我可以这样称呼它吗:

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

或者

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

推荐答案

C++ 中没有命名函数参数,但是你可以使用 C++20 中的指定初始化器实现类似的效果.

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{};
};

现在修改您的函数以获取该结构的实例(通过 const& 提高效率)

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

这是一个演示

相关文章