当对数组使用 typedef 时,它被用作
typedef int Color[3];
这对我来说非常违反直觉。
为什么不typedef int[3] Color[3]?
typedef
看起来就像一个普通的变量声明,而这恰好是数组声明在 C 中的样子(并继承到 C++ 中):
int foo[3]; // Array of three int
typedef int FooT[3]; // typedef for array of three int.
恐怕这就是语言的定义方式。如果有帮助,typedef
语法看起来就像声明语法:
int Color[3];
将创建一个由三个整数组成的数组,因此:
typedef int Color[3];
Typedefs 一个由三个整数组成的数组。
语法匹配的一个方便的优点是您可以使用类似的工具cdecl(1)
为您生成或解释它们:
cdecl> explain int Color[3]
declare Color as array 3 of int
cdecl> declare Color as array 3 of int
int Color[3]
Typedef 就像一个变量定义一样工作,并遵循所有相同的规则(已经建立和已知的规则),唯一的区别是它不是变量名,而是表示类型。
我想说,与其实现一些新的方案(这将不得不处理所有微妙的事情,例如,指向数组的指针与指针数组),使用现有的方案是明智的选择。
我建议使用
typedef std::array<int,3> RGB_Type;
这与其他 C++ 标准容器的 typedef 一致。
(抱歉,仅限 C++,但标题中提到了这一点。)
In C++11 you can create a syntax that does close to what you want:
template<typename T>
using type_def = T;
type_def<int[3]> colors;
At first glance, I would recommend against it: on the other hand, some really complex type declarations could be simplified a lot via this mechanism. Getting rid of "placeholder" typedef
in complex types whose purpose is only to make the final type look more readable.