原文:http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Default_Arguments
Default argument的好處在於,你不必再為了一些罕見的special case而另外寫一個function,直接使用default argument即可。而且default argument和function overloading比起來,default argument可以用更清楚的方式來分區必要的(required)和非必要的(optional)引數。
Default argument的壞處在於,和function pointer一起使用時會出問題:
typedef void (*PFN)(int);
void Foo(int a = 10)
{
cout << a << endl;
}
void main()
{
PFN pfn = Foo;
pfn();
}
以上程式在VS 2008會出現以下compile error:
error C2198: 'PFN' : too few arguments for call
所以當加入一個default argument到現有的function時,可能就會引發上述的compile error。(如果該function有透過function pointer來呼叫的話)
除此之外更動default argument會影響每一個呼叫該function的地方(call site),使用function overloading則沒有這個問題。
由於使用default argument的缺點大於優點,Google C++ Style Guide禁止使用default argument。必要時,你可以自行使用function overloading來模擬default argument。
以下是Google C++ Style Guide指出可以使用default argument的少數例外:
1. 當該function為static function時,此時上述的缺點將不存在。
2. 當透過default argument來模擬variable-length argument lists時:
// Support up to 4 params by using a default empty AlphaNum.
string StrCat(const AlphaNum &a,
const AlphaNum &b = gEmptyAlphaNum,
const AlphaNum &c = gEmptyAlphaNum,
const AlphaNum &d = gEmptyAlphaNum);
- Mar 22 Fri 2013 23:01
Default argument
close
文章標籤
全站熱搜
留言列表
發表留言