17 January 2023

C++ 核心指南目录

“Overload only for operations that are roughly equivalent”

理由

逻辑上相似的操作函数,使用不同的参数类型,却用了不同的名字,容易让人费解。在使用泛型编程的时候,容易出错。

例子

考虑:

void open_gate(Gate& g);   // remove obstacle from garage exit lane
void fopen(const char* name, const char* mode);   // open file

这两个函数完全不同且不相关,所以名字也不一样。

相反的:

void open(Gate& g);   // remove obstacle from garage exit lane
void open(const char* name, const char* mode ="r");   // open file

这两个函数也是完全不同不想管的,但是名字却取的一样,这样很容易令人误解。好在类型系统会捕捉相关的错误。

注意

一定要小心一些常用的名字,比如 open, move, +, ==。