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

In C ++, functions with multiple arguments, I would like one of the arguments to have a default value, which itself is a function of the other arguments. For instance,

int f1( int m ); int f2( int n1, int n2 = f1( n1 ) ) { // Do stuff with n1 and n2 } 

This does not compile, but hopefully it clearly shows the behavior I want for the f2 function. His caller should be able to manually pass the value for n2 to him, but by default, the value of n2 should be determined by calling f1 on n1. What are some suggestions on how best to implement (or at least approximate) this behavior?

+4
source share
4 answers

Instead, reload the function:

 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 ) ); } 
+6
source

Instead, you can use function overloading.

 int f2(int n1) { return f2(n1, f1(n1)); } int f2(int n1, int n2) { // do stuff } 
+4
source

One solution is to overload functions, as other answers have said.

Another solution is to use boost::optional for an optional argument:

 int f2( int n1, boost::optional<int> n2) { int n2value = n2 != boost::none? n2.get() : f1(n1); //use n1 and n2value in the rest of the function! } 

boost::optional usually helps when you have a few optional arguments, for example:

 int f(int a, boost::optional<X> b, boost::optional<Y> c, boost::optional<Z> d) { //etc } 

In such a situation, the overload function explodes, as the number of functions increases linearly with each additional optional parameter. Fortunately, C ++ does not have a named parameter, otherwise it will increase exponentially, not linearly. :-)

+2
source

This may not be a very good approach, but you can also use templates, for example:

Similar to the default comparison function in associated STL containers (map, set, etc.)

 struct f1{ int operator() (int m) const { //definition for f1 goes here }; }; struct f3{ int operator() (int m) const { //definition for any other f3 goes here }; }; template < class fun = f1> int f2( int n1, const fun& f=fun() ) { int x=f(n1); //std::cout<<x<<std::endl; } int main() { f2<f3>(11); //Call using f3 f2(12); // Call using default f1 } 
0
source

Source: https://habr.com/ru/post/1494563/


All Articles