Reputation: 955
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
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