假设有一个具有默认值的函数:
int foo(int x=42);
如果这是由其他人这样调用:
int bar(int x=42) { return foo(x); }
int moo(int x=42) { return bar(x); }
这当然只是一个人为的例子.但是,我有时情况非常相似.该参数仅从最高级别(moo)传递到最低级别,并且仅在实际使用时才传递.关于这一点的坏处是,当我改变foo以使默认值不同于42时,我将不得不搜索所有调用者并相应地更改默认值.
是否有一些模式/成语可以避免这种情况?
我想到的唯一简单的解决方案是
int bar() { return foo(); }
int bar(int x) { return foo(x); }
但是,由于我有点懒,而且在实际代码中这会导致相当多的代码重复,我想避免这种情况.
解决方法
实用的一般解决方案包括:
>对参数使用Optional_类,例如boost :: optional或DIY等效项.
>命名默认值(并使用包装函数定义中的名称).
>如您在问题中所示,重载每个包装函数.
>只需重复包装函数定义中的默认值,但这会打破DRY原则,不要重复自己.
在comment else-thread中,Tobi提出了asdf定义为包装器的情况
int asdf(int x=42,int y=42){ return foo(x)+foo(y);}
使用Optional_类:
auto foo( Optional_<int> x)
-> int
{ return (x.is_empty()? 42 : x.value()); }
auto asdf( Optional_<int> x = {},Optional_<int> y = {} )
-> int
{ return foo( x ) + foo( y ); }
使用命名的默认值:
int const foo_default = 42;
auto foo( int x = foo_default )
-> int
{ return x; }
auto asdf( int x = foo_default,int y = foo_default )
-> int
{ return foo( x ) + foo( y ); }
使用重载:
auto foo( int x = 42 )
-> int
{ return x; }
auto asdf()
-> int
{ return foo() + foo(); }
auto asdf( int x )
-> int
{ return foo( x ) + foo(); }
auto asdf( int x,int y )
-> int
{ return foo( x ) + foo( y ); }
值得注意的是,asdf不能轻易定义为转发其参数的函数模板.而且,这样的模板不能在单独的翻译单元中容易地定义,并且不能采用其地址.由于这些原因,我没有在子弹列表中包含这种可能的解决方案:它非常有限,而不是一般解决方案.