NL.5:避免在名称中包含类型信息
If names reflect types rather than functionality, it becomes hard to change the types used to provide that functionality. Also, if the type of a variable is changed, code using it will have to be modified. Minimize unintentional conversions.
如果名称反映类型而不是功能,则很难更改用于提供该功能的类型。同样,如果更改了变量的类型,则必须修改使用该变量的代码。最小化意外转换。
Example, bad(反面示例)
void print_int(int i);
void print_string(const char*);
print_int(1); // repetitive, manual type matching
print_string("xyzzy"); // repetitive, manual type matching
void print(int i);
void print(string_view); // also works on any string-like sequence
print(1); // clear, automatic type matching
print("xyzzy"); // clear, automatic type matching
Names with types encoded are either verbose or cryptic.
包含类型的名称是冗长的或隐秘的。
printS // print a std::string
prints // print a C-style string
printi // print an int
Requiring techniques like Hungarian notation to encode a type has been used in untyped languages, but is generally unnecessary and actively harmful in a strongly statically-typed language like C++, because the annotations get out of date (the warts are just like comments and rot just like them) and they interfere with good use of the language (use the same name and overload resolution instead).
在非类型化语言中已经使用了像匈牙利命名方法这样的技术在变量名中包含类型,但是在像C ++这样的强静态类型化语言中,这通常是不必要的甚至是有害的,因为注释已经过时了(注释就像疣一样,也会像它们一样腐烂),并且会干扰语言的良好使用(改用相同的名称并使用重载方式)。
Note(注意)
Some styles use very general (not type-specific) prefixes to denote the general use of a variable.
一些样式使用非常通用的(不是特定于类型的)前缀来表示变量的通用用法。
auto p = new User();
auto p = make_unique<User>();
// note: "p" is not being used to say "raw pointer to type User,"
// just generally to say "this is an indirection"
auto cntHits = calc_total_of_hits(/*...*/);
// note: "cnt" is not being used to encode a type,
// just generally to say "this is a count of something"
This is not harmful and does not fall under this guideline because it does not encode type information.
这是无害的,并且不受该准则约束,因为它表达的不是类型信息。
Note(注意)
Some styles distinguish members from local variable, and/or from global variable.
一些风格将成员与局部变量和/或全局变量区分开。
struct S {
int m_;
S(int m) : m_{abs(m)} { }
};
This is not harmful and does not fall under this guideline because it does not encode type information.
这是无害的,不受该准则约束,因为它没有表达类型信息。
Note(注意)
Like C++, some styles distinguish types from non-types. For example, by capitalizing type names, but not the names of functions and variables.
像C ++一样,某些风格将类型与非类型区分开。例如,通过大写类型名称,而不是函数和变量的名称。
typename<typename T>
class HashTable { // maps string to T
// ...
};
HashTable<int> index;
This is not harmful and does not fall under this guideline because it does not encode type information.
这是无害的,不受该准则约束,因为它没有表达类型信息。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nl5-avoid-encoding-type-information-in-names