问题
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?
回答1:
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 ) );
}
回答2:
You could instead use function overloading.
int f2(int n1) {
return f2(n1, f1(n1));
}
int f2(int n1, int n2) {
// do stuff
}
回答3:
One solution is function overloading as other answers has already suggested.
Other solution is to use boost::optional
type for the 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 more than one optional arguments, e.g:
int f(int a, boost::optional<X> b, boost::optional<Y> c, boost::optional<Z> d)
{
//etc
}
In such situation function overloading explodes, as the number of functions increases linearly with each additional optional parameter. Thankfully, C++ doesn't have named-parameter, otherwise it would increase exponentially instead of linearly. :-)
回答4:
This might not be the good approach but you also can utilize templates like following:
Similar to the default compare functions in Associate 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
}
来源:https://stackoverflow.com/questions/17978790/how-to-give-an-argument-a-default-value-determined-by-a-function-of-the-other-ar