这种类型的意思是什么,有什么好处?

时间:2013-07-22 22:23:12

标签: c++ templates metaprogramming

我偶然发现了这个typedef:

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

我知道&作为参考限定符或运算符地址。既然我们在这里处理类型,我猜它是一个参考,但括号有特殊用途吗?

在上下文中,我从中获取它用于执行类型可转换性的编译时检查,这种typedef如何帮助解决这个问题?

2 个答案:

答案 0 :(得分:6)

typedef定义对char数组的引用:small是一个charlarge的数组,作为两个{{1}的数组}}。这种char s的目的是让它们基于重载从属性检查器返回:如果属性存在,则返回一个,否则返回另一个。然后使用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为1和2)。使用例如内置类型的大小不能可靠地工作,因为它们都可以具有相同的大小。

...而且,是的,括号内容:没有括号,创建引用数组而不是对数组的引用将是非法尝试。只有后者给出尺寸保证,这是后续的。

答案 1 :(得分:1)

这些语句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])
{ ... }
相关问题