In a C++ function with multiple arguments, I would like one of the arguments to have a default value which is itself a function of the other arguments. For example,
int f1( int m );
int f2( int n1, int n2 = f1( n1 ) ) {
// Do stuff with n1 and n2
}
This won't compile, but hopefully it makes clear the behavior I want for the function f2. Its caller should be able to manually pass it a value for n2, but by default the value of n2 should be determined by calling f1 on n1. What are some suggestions for how best to implement (or at least approximate) this behavior?
Overload the function instead:
int f1( int m );
int f2( int n1, int n2 ) {
// Do stuff with n1 and n2
}
int f2( int n1 ) {
return f2( n1, f1( n1 ) );
}
You could instead use function overloading.
int f2(int n1) {
return f2(n1, f1(n1));
}
int f2(int n1, int n2) {
// do stuff
}
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