C++核心准则F.51:如果可以,优先选择缺省参数而不是重载

面向对象思考

共 1575字,需浏览 4分钟

 · 2019-12-01

f5df7bd0d21fb7fdba9668607347131a.webp

F.51: Where there is a choice, prefer default arguments over overloading
F.51:如果可以,优先选择缺省参数而不是重载

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.

缺省参数简单地为同一个实现提供不同的接口。无法保证所有的重载函数都会按照同样的语义实现。使用缺省参数可以避免这种重复。

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:

有一种情况确实需要在使用缺省参数和重载之间做出选择:不同接口之间的区别来自一系列具有相同类型的参数。

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:

当一系列函数针对不同的类型执行语义上等价的操作时应该使用重载。例如:

void print(const char&);void print(int);void print(zstring)


See also

参见

Default arguments for virtual functions

虚函数的缺省参数

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.)

    当一系列重载之间具有共同的前缀参数(例如:f(int),f(int, const string&),f(int, const string&, double))。(注意:如果在实践中存在太多的杂音(反对意见),重新审视本规则。)


觉得本文有帮助?请分享给更多人

关注【面向对象思考】,每天前进一小步

有任何疑问,欢迎留言提问或讨论




面向对象设计,面向对象编程,面向对象思考!



浏览 10
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报