我不熟悉 cpp 中的模板魔术。在阅读了 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 是如何工作的,以及 traits 是如何工作的。在引用 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 我们有:
Checks whether T is an integral type. Provides the member constant value which is equal to true, if T is the type
bool
,char
,char16_t
,char32_t
,wchar_t
,short
,int
,long
,long long
, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants. Otherwise, value is equal to 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>> {};
// ...
请注意,
std::false_type
和 std::true_type
是 std::integral_constant
的特化。有关更多详细信息,请参阅 here。
关于c++11 - std::is_integral 是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43571962/