`int typedef my_int;` 形式的 Typedef 声明

Typedef declaration in the form `int typedef my_int;`

要将 my_int 声明为 int 的类型别名,我们可以这样写:

typedef int my_int;   // (1)

奇怪的是,下面似乎也定义了一个 int 别名:

int typedef my_int;   // (2)

我以前从未见过这样的语法。为什么有效?

我阅读 C++ reference 后的推理是这样的:(1) 和 (2) 是

形式的声明
specifiers-and-qualifiers declarators-and-initializers;

其中 specifiers-and-qualifierstypedef intint typedef

说明符和限定符的顺序无关紧要,(1) 和 (2) 都是类型别名的有效声明。例如,要为 const int 定义别名,原则上我们可以使用以下 6 种组合中的任何一种:

typedef int const my_cint;
typedef const int my_cint;
int typedef const my_cint;
const typedef int my_cint;
int const typedef my_cint;
const int typedef my_cint;

的确,您的解释是正确的here

The typedef specifier, when used in a declaration's decl-specifier-seq, specifies that the declaration is a typedef declaration, and declares typedef-names rather than functions or objects.

然而,在现代 C++ 中,type alias 最好用 using 子句定义:

using my_int = int; 

这不仅仅是样式问题:typedef 不支持模板化,而类型别名支持:

template <typename T>
using my_list = list<T>;   // not possible with typedef
...
my_list<double> numbers;