最好的 "type renaming" 方法是什么?

What's the best "type renaming" method?

如果我想将 std::string 类型重命名为更简单、看起来更自然的 string,我应该使用这两种方法中的哪一种(基于性能和通常的标准)

我是否应该将其重命名为预处理指令

#define string std::string

或者用类型定义来做

typedef std::string string;

最高效的方法是什么?还有什么比较为社区所熟悉和认可的?

刚刚

using std::string;

如果您想要一个略有不同的名称,例如

using String = std::string;

避免使用宏,它们不考虑作用域并且通常是 Evil™。

例如建议的宏

#define string std::string

... 如果包含任何标准库头文件,则会产生正式的未定义行为,因为它定义了标准库使用的名称。

C++11 §17.6.4.2.2/1 [macro.names]:

A translation unit that includes a standard library header shall not #define or #undef names declared in any standard library header.

如果你只是不想写命名空间

,你应该使用using
using std::string;

两者都不会更高效,因为它们都是编译时的。

对于更复杂的情况,您可以使用其他形式的 using

using short_name = complex_name<possibly, with, templates>;

写作

using std::string;

是最好的方法。这具有将标准 C++ 库字符串 class 带入当前命名空间的效果。

但实际上您应该学会流利地阅读包含范围解析运算符的代码。写作中

std::string

阅读您的代码的人确切地知道发生了什么。