前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则F.51:如果可以,优先选择缺省参数而不是重载

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

作者头像
面向对象思考
发布2020-03-25 15:38:16
3730
发布2020-03-25 15:38:16
举报
文章被收录于专栏:C++核心准则原文翻译

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:

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

代码语言:javascript
复制
void print(const string& s, format f = {});

as opposed to

而不是

代码语言:javascript
复制
void print(const string& s);  // use default format
void 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:

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

代码语言:javascript
复制
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))。(注意:如果在实践中存在太多的杂音(反对意见),重新审视本规则。)

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

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

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


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

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-12-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.51: Where there is a choice, prefer default arguments over overloading F.51:如果可以,优先选择缺省参数而不是重载
    • Reason(原因)
      • Note(注意)
        • See also
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档