C++核心準(zhǔn)則F.51:如果可以,優(yōu)先選擇缺省參數(shù)而不是重載

F.51: Where there is a choice, prefer default arguments over overloading
F.51:如果可以,優(yōu)先選擇缺省參數(shù)而不是重載
Reason(原因)
Default arguments simply provide alternative interfaces to a single implementation. There is no guarantee that a set of overloaded functions all implement the same semantics. The use of default arguments can avoid code replication.
缺省參數(shù)簡單地為同一個實現(xiàn)提供不同的接口。無法保證所有的重載函數(shù)都會按照同樣的語義實現(xiàn)。使用缺省參數(shù)可以避免這種重復(fù)。
Note(注意)
There is a choice between using default argument and overloading when the alternatives are from a set of arguments of the same types. For example:
有一種情況確實需要在使用缺省參數(shù)和重載之間做出選擇:不同接口之間的區(qū)別來自一系列具有相同類型的參數(shù)。
void print(const string& s, format f = {});as opposed to
而不是
void?print(const?string&?s);??//?use?default?formatvoid print(const string& s, format f);
There is not a choice when a set of functions are used to do a semantically equivalent operation to a set of types. For example:
當(dāng)一系列函數(shù)針對不同的類型執(zhí)行語義上等價的操作時應(yīng)該使用重載。例如:
void print(const char&);void?print(int);void?print(zstring)
See also
參見
Default arguments for virtual functions
虛函數(shù)的缺省參數(shù)
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rh-virtual-default-arg
Enforcement(實施建議)
Warn on an overload set where the overloads have a common prefix of parameters (e.g.,
f(int),f(int, const string&),f(int, const string&, double)). (Note: Review this enforcement if it's too noisy in practice.)當(dāng)一系列重載之間具有共同的前綴參數(shù)(例如:f(int),f(int, const string&),f(int, const string&, double))。(注意:如果在實踐中存在太多的雜音(反對意見),重新審視本規(guī)則。)
覺得本文有幫助?請分享給更多人
關(guān)注【面向?qū)ο笏伎肌?,每天前進(jìn)一小步
有任何疑問,歡迎留言提問或討論
面向?qū)ο笤O(shè)計,面向?qū)ο缶幊?,面向?qū)ο笏伎迹?/p>
