Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give an argument a default value determined by a function of the other arguments

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?

like image 842
harold Avatar asked Dec 16 '22 08:12

harold


2 Answers

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 ) );
}
like image 148
DaoWen Avatar answered Mar 02 '23 01:03

DaoWen


You could instead use function overloading.

int f2(int n1) {
    return f2(n1, f1(n1));
}

int f2(int n1, int n2) {
    // do stuff
}
like image 20
Drew McGowen Avatar answered Mar 02 '23 00:03

Drew McGowen