Typedef声明,形式为`int typedef my_int;`

问题描述 投票:0回答:1

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

typedef int my_int;   // (1)

奇怪的是,以下内容似乎也定义了int别名:

int typedef my_int;   // (2)

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

c++ typedef
1个回答
2
投票

实际上,您的解释是正确的,如here所述:

typedef说明符,在声明的decl-specifier-seq,指定声明为typedef声明,并声明typedef名称而不是函数或对象。

尽管如此,在现代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; 

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;
© www.soinside.com 2019 - 2024. All rights reserved.