#include
#include
int main()
{
std::cout << std::is_void<void>::value;// 1
std::cout << std::is_void<int>::value; // 0
return 0;
}
查看is_void源码为:
template<class _Ty>
struct is_void
: false_type
{ // determine whether _Ty is void
};
#define _IS_VOID(CV_OPT) \
template<> \
struct is_void \
: true_type \
{ /* determine whether _Ty is void */ \
};
_CLASS_DEFINE_CV(_IS_VOID)
#undef _IS_VOID
即为:特化模板参数,void是继承自true_type,否则继承自false_type,有点思路了,但是这两者是什么呢?
// ALIAS TEMPLATE bool_constant
template<bool _Val>
using bool_constant = integral_constant<bool, _Val>;
using true_type = bool_constant<true>;
using false_type = bool_constant<false>;
继续刨根问底到 integral_constant:
template<class _Ty,_Ty _Val>
struct integral_constant
{
// convenient template for integral constant types
static constexpr _Ty value = _Val;
using value_type = _Ty;
using type = integral_constant;
constexpr operator value_type() const noexcept
{ // return stored value
return (value);
}
_NODISCARD constexpr value_type operator()() const noexcept
{ // return stored value
return (value);
}
};
这里面 static constexpr _Ty value = _Val;
显而易见的定义了一个静态的bool类型变量,这时候再看到,恍然大悟。
template<bool _Val>
using bool_constant = integral_constant<bool, _Val>;
using true_type = bool_constant<true>;
using false_type = bool_constant<false>;
总之,就是使用模板编程和继承的技巧,在编译器实现了这样的效果。