4

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);
cigien
  • 57,834
  • 11
  • 73
  • 112
mooko
  • 109
  • 1
  • 4
  • 1
    [Aggregate inits](https://en.cppreference.com/w/cpp/language/aggregate_initialization) can have designators, but it's a C++20 feature. – m88 Feb 07 '21 at 22:02
  • 1
    take a look at https://www.fluentcpp.com/2018/12/14/named-arguments-cpp/ – Severin Pappadeux Feb 07 '21 at 22:08
  • @SamVarshavchik The target is incorrect. The OP doesn't want to know why the language doesn't support this. They're asking for a workaround. I'm reopening. – cigien Feb 07 '21 at 22:18

2 Answers2

13

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

cigien
  • 57,834
  • 11
  • 73
  • 112
  • Thanks for the answer and It seems like a neat approach. But can it be referred to as a good practice or would it be referred to as a gimmick? – vhmvd May 08 '22 at 12:45
  • 1
    @Ahmn21 It's a relatively modern feature, as it's only been in the language for a few years, so it's a bit early to say if this is good practice. However, it's perfectly valid code, and I would say it's quite a reasonable way to achieve something like named parameters. There aren't any downsides to this approach as far as I'm aware. – cigien May 08 '22 at 16:17
3

No
You have to pass the arguments by order, so, to specify a value for d, you must also specify one for c since it's declared before it, for example

Educorreia
  • 375
  • 5
  • 21