c++11 - std::is_integral 是如何实现的?

标签 c++11 templates typetraits

我不熟悉 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_typestd::true_typestd::integral_constant 的特化。有关更多详细信息,请参阅 here

关于c++11 - std::is_integral 是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43571962/

相关文章:

c++ - 在不创建参数对象的情况下解析 constexpr 函数

c++ - 为什么迭代时不能使用模板

c++ - 普通类型的类型特征

c++ - 可能吗? std::vector<双> my_vec(sz);已分配但未初始化或填充

c++11 - QTextDocument::print 中的段错误

c++ - 如果一个类型 `T` 有一个 `template<> struct Writer<T>` 来序列化自己

css - 修改 Visual Studio 2013 MVC Web 元素模板 CSS

c++ - 替换失败

c++ - 有条件地重载运算符

c++ - 为什么 C++11 中没有模板化的 typedef?