C.163: 重载只用于基本等价的操作
Having the same name for logically different functions is confusing and leads to errors when using generic programming.
逻辑上不同的函数使用相同的名称会引起混淆,在使用它们进行共通化编程时容易引发错误。
Example(示例)
Consider(考虑下面的代码):
void open_gate(Gate& g); // remove obstacle from garage exit lane
void fopen(const char* name, const char* mode); // open file
The two operations are fundamentally different (and unrelated) so it is good that their names differ. Conversely:
两个操作是根本不同的(也没有关联),因此它们使用不同的名称就很好。相反:
void open(Gate& g); // remove obstacle from garage exit lane
void open(const char* name, const char* mode ="r"); // open file
The two operations are still fundamentally different (and unrelated) but the names have been reduced to their (common) minimum, opening opportunities for confusion. Fortunately, the type system will catch many such mistakes.
这还是两个根本不同的操作(而且毫无关联),但是名称已经被压缩到(共通的)最小限度,这种做法增加了混淆的可能性。幸运的是,很多这样的错误都会被系统捕捉到。
Note(注意)
Be particularly careful about common and popular names, such as open, move, +, and ==.
特别关注那些通用和常见的名字,例如open,move,+和==等。
Enforcement(实施建议)
???
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c163-overload-only-for-operations-that-are-roughly-equivalent
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!