在 C++ 中有没有办法像在 python 中那样按名称传递参数? [英] Is there a way in C++ to pass arguments by name like in python?

查看:36
本文介绍了在 C++ 中有没有办法像在 python 中那样按名称传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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

这是一个演示

这篇关于在 C++ 中有没有办法像在 python 中那样按名称传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆