我对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是boolcharchar16_tchar32_twchar_tshortintlong,或任何实现定义的扩展整数类型,包括任何有符号,无符号和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 longstd::false_typestd::true_type的特化。有关更多详细信息,请参见here

07-28 01:32
查看更多