这个typedef是什么意思,它有什么好处

What does this typedef mean and what is it good for?

本文关键字:什么 typedef 是什么 意思 这个      更新时间:2023-10-16

我偶然发现了这个typedef:

typedef char (&small)[1];
typedef char (&large)[2];

我知道&要么是引用限定符,要么是运算符的地址。既然我们在这里处理类型,我想这是一个引用,但括号有特殊用途吗?

在我得到它的上下文中,它用于执行编译时检查类型的可转换性,这个typedef在这方面有什么帮助?

typedef定义了对char数组的引用:small是一个char的数组,large是两个char的数组。这类typedef的目的是让它们从基于重载的属性检查器中返回:如果属性存在,则返回一个,否则返回另一个。然后使用结果sizeof()来确定属性,例如:

template <typename B, typename S>
struct is_base_of_helper {
    static small test(B*);
    static large test(void*, ...);
};
template <typename B, typename S>
struct is_base_of {
    enum value { 1 == sizeof(is_base_of_helper<B, S>::test(static_cast<S*>(0)) };
};

测试在语义上可能不太准确,但其想法是:在sizeof()操作中调用重载函数并测试结果的大小。根据所选择的重载,可以确定类型属性的存在。使用对数组的引用有一个很好的特性,即可以预测它们的大小(smalllarge分别为1和2)。例如,使用内置类型的大小并不可靠,因为它们可能都有相同的大小。

是的,括号很重要:如果没有括号,创建引用数组而不是对数组的引用将是非法的。只有后者提供了这之后的尺寸保证。

这些语句typedef分别引用大小为1和2的数组。这是一个例子:

/*
 foo accepts arrays of size 10 only!
*/
void foo(int (&array)[10])
{ ... }

另一个例子:

/*
 foo accepts arrays of size len!
 The size is len, so you can know the size of the array
 unlike when using a pointer to int.
 (unless you pass the size in the next parameter, of course!)
*/
template <std::size_t len>
void foo(int (&array)[len])
{ ... }