【问题标题】:How to give an argument a default value determined by a function of the other arguments如何给一个参数一个由其他参数的函数确定的默认值
【发布时间】:2013-08-01 11:23:57
【问题描述】:
在具有多个参数的 C++ 函数中,我希望其中一个参数具有默认值,该值本身就是其他参数的函数。例如,
int f1( int m );
int f2( int n1, int n2 = f1( n1 ) ) {
// Do stuff with n1 and n2
}
这不会编译,但希望它能明确我想要函数 f2 的行为。它的调用者应该能够手动将 n2 的值传递给它,但默认情况下,n2 的值应该通过在 n1 上调用 f1 来确定。对于如何最好地实现(或至少近似)这种行为有什么建议?
【问题讨论】:
标签:
c++
function
default-value
【解决方案1】:
您可以改为使用函数重载。
int f2(int n1) {
return f2(n1, f1(n1));
}
int f2(int n1, int n2) {
// do stuff
}
【解决方案2】:
重载函数:
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 ) );
}
【解决方案3】:
一个解决方案是函数重载,正如其他答案已经建议的那样。
其他解决方案是使用boost::optional 类型作为可选 参数:
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 通常在您有多个可选参数时会有所帮助,例如:
int f(int a, boost::optional<X> b, boost::optional<Y> c, boost::optional<Z> d)
{
//etc
}
在这种情况下,函数重载会爆炸式增长,因为函数的数量会随着每个额外的可选参数线性增加。值得庆幸的是,C++ 没有命名参数,否则它会指数地而不是线性地增加。 :-)
【解决方案4】:
这可能不是好方法,但您也可以使用以下模板:
类似于 Associate STL Containers 中的默认比较函数(map、set 等)
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
}