template<class T>
struct is_class_or_union
{
struct twochar { char _[2]; };
template <class U>
static char is_class_or_union_tester(void(U::*)(void));
template <class U>
static twochar is_class_or_union_tester(...);
static const bool value = sizeof(is_class_or_union_tester<T>(0)) == sizeof(char);
};
上述代码来自boost库的meta_utils.hpp
。Boost代码摘录 - 无法理解
is_class_or_union_tester
似乎是一个static
函数返回char
并采取指针成员函数(返回void并接受无)。没有功能体,它似乎没有在其他地方定义。我不明白它是如何工作的,而且最重要的是,我不明白该功能的用途。- 我不明白以下代码的概念:
static const bool value = sizeof(is_class_or_union_tester<T>(0)) == sizeof(char);
sizeof
运算符应用于什么?他们想在这里找到什么?
[C++ SFINAE示例?]的可能的重复(http://stackoverflow.com/questions/982808/c-sfinae-examples) – soon
@peter感谢您的解释。它当然有帮助。我不知道没有链接器错误(对于函数定义),因为该函数从未被调用? –
没有链接器错误,因为实际上没有创建代码。 'sizeof'实际上并不执行它传递的表达式,而是计算出结果的类型,然后计算它的大小。 –