Here is a function declaration with default arguments:
void func(int a = 1,int b = 1,...,int x = 1)
How can avoid calling func(1,1,...,2)
when I only want to set the x
parameter and for the rest with the previous default params?
For example, just like func(paramx = 2, others = default)
You can't do this as part of the natural language. C++ only allows you to default any remaining arguments, and it doesn't support named arguments at the calling site (cf. Pascal and VBA).
An alternative is to provide a suite of overloaded functions.
Else you could engineer something yourself using variadic templates.
Bathsheba already mentioned the reason why you can not do that.
One solution to the problem could be packing all parameters to a struct
or std::tuple
(using struct
would be more intuitive here) and change only the values what you want. (If you are allowed to do that)
Following is example code:
#include <iostream>
struct IntSet
{
int a = 1; // set default values here
int b = 1;
int x = 1;
};
void func(const IntSet& all_in_one)
{
// code, for instance
std::cout << all_in_one.a << " " << all_in_one.b << " " << all_in_one.x << std::endl;
}
int main()
{
IntSet abx;
func(abx); // now you have all default values from the struct initialization
abx.x = 2;
func(abx); // now you have x = 2, but all other has default values
return 0;
}
Output:
1 1 1
1 1 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With