这个typedef是什么意思,它有什么好处
What does this typedef mean and what is it good for?
我偶然发现了这个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()
操作中调用重载函数并测试结果的大小。根据所选择的重载,可以确定类型属性的存在。使用对数组的引用有一个很好的特性,即可以预测它们的大小(small
和large
分别为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])
{ ... }
相关文章:
- typedef 枚举和枚举类有什么区别?
- C++中"typedef"、"using"、"namespace"和"using namespace"有什么区别?
- 使用typedef有什么用,它意味着什么
- 这个typedef和转换运算符语法是什么意思
- 对于指向C++类的不透明C指针,正确的typedef是什么
- 使用 pybind11 绑定 typedef 类型的正确语法是什么?
- 返回没有 typedef 的成员函数指针的语法是什么?
- typedef 在类中有什么用
- 在Visual Studio中定义与Typedef枚举发生冲突的原因是什么?
- 在Typedef结构中,下划线意味着什么
- 在 typedef 中有三个元素是什么意思 C++.
- typedef和enum之间的区别是什么
- 如[dcl.typedef]/9所述,仅针对"linkage purposes"的链接声明的目的是什么?
- 使用 typedef 创建节点有什么优势?
- 这个 typedef 语句中的语法在做什么
- typedef void (*MyCallback) : 它是什么以及如何使用它
- 这个 typedef 定义是什么意思
- 以下 typedef 在 chrono::d uration 中是什么意思
- 函数指针typedef的语法是什么
- "typedef"在C++中有什么特殊意义吗?