我对cpp中的Template magic不熟悉。读完link中“ TemplateRex”的内容后,我对std :: is_intergral的工作方式感到困惑。
template< class T >
struct is_integral
{
static const bool value /* = true if T is integral, false otherwise */;
typedef std::integral_constant<bool, value> type;
};
我可以理解SFINAE的工作原理和特质的工作原理。引用cppreference后,发现实现了“ is_pointer”而不是“ is_integral”,如下所示:
template< class T > struct is_pointer_helper : std::false_type {};
template< class T > struct is_pointer_helper<T*> : std::true_type {};
template< class T > struct is_pointer : is_pointer_helper<typename std::remove_cv<T>::type> {};
'is_integral'是否具有类似的实现?怎么样?
最佳答案
从here我们有:
检查T是否为整数类型。如果T是bool
,char
,char16_t
,char32_t
,wchar_t
,short
,int
,long
,或任何实现定义的扩展整数类型,包括任何有符号,无符号和cv限定的变体。否则,值等于false。
这样的事情大概是在您实现它的过程中:
template<typename> struct is_integral_base: std::false_type {};
template<> struct is_integral_base<bool>: std::true_type {};
template<> struct is_integral_base<int>: std::true_type {};
template<> struct is_integral_base<short>: std::true_type {};
template<typename T> struct is_integral: is_integral_base<std::remove_cv_t<T>> {};
// ...
请注意,
long long
和std::false_type
是std::true_type
的特化。有关更多详细信息,请参见here。