user11914177
user11914177

Reputation: 955

How to only use some of the optional arguments of a function

Is there a way to only use some optional arguments of a function? So if I have a function like this,

void f(int a = 0, int b = 1) {}

can I call f() and only specify b and leave a on its default value?

Upvotes: 2

Views: 1277

Answers (1)

AndyG
AndyG

Reputation: 41100

I wish. C++ lacks this feature that is common in other languages (like C# or Python).

For now, you are stuck with either being very clever about designing the order of your parameters, or refactoring your parameters into a small struct:

struct f_args
{
   int a = 0;
   int b = 1;
};

Now you can optionally set whatever you want:

void f(f_args args){/*...*/};

// ...
f_args args;
args.b = 2;
f(args);

Or with designated initializers (C++20):

f({.b=2});

The Boost parameter library attempts to tackle this problem in a more robust way.

Upvotes: 7

Related Questions