C++ 类型特征(Type Traits)

 

分类类型特征描述C++标准_v写法(C++17)
基本类型特性检查      std::is_same<T1, T2>::value 检查两个类型是否相同 C++11 std::is_same_v<T1, T2>
std::is_integral<T>::value 检查T是否为整数类型 C++11 std::is_integral_v<T>
std::is_floating_point<T>::value 检查T是否为浮点类型 C++11 std::is_floating_point_v<T>
std::is_array<T>::value 检查T是否为数组类型 C++11 std::is_array_v<T>
std::is_pointer<T>::value 检查T是否为指针类型 C++11 std::is_pointer_v<T>
std::is_void<T>::value 检查T是否为void类型 C++11 std::is_void_v<T>
类型属性检查    std::is_const<T>::value 检查T是否为常量类型 C++11 std::is_const_v<T>
std::is_volatile<T>::value 检查T是否为易变类型 C++11 std::is_volatile_v<T>
std::is_signed<T>::value 检查T是否为有符号类型 C++11 std::is_signed_v<T>
std::is_unsigned<T>::value 检查T是否为无符号类型 C++11 std::is_unsigned_v<T>
类型修改       std::add_const<T> 为类型T添加const修饰符 C++11 -
std::remove_const<T> 从类型T中移除const修饰符 C++11 -
std::add_volatile<T> 为类型T添加volatile修饰符 C++11 -
std::remove_volatile<T> 从类型T中移除volatile修饰符 C++11 -
std::add_pointer<T> 为类型T添加指针 C++11 -
std::remove_pointer<T> 从类型T中移除指针 C++11 -
std::remove_reference<T> 从类型T中移除引用修饰符 C++11 -
关系检查  std::is_base_of<Base, Derived>::value 检查Base是否是Derived的基类 C++11 std::is_base_of_v<Base, Derived>
std::is_convertible<From, To>::value 检查类型From是否可以转换为类型To C++11 std::is_convertible_v<From, To>
复合类型特性  std::tuple_size<T>::value 获取元组T的大小 C++11 std::tuple_size_v<T>
std::tuple_element<I, T>::type 获取元组T中第I个元素的类型 C++11 -
高级特性    std::void_t<Ts...> 用于推导void类型 C++17 -
std::conjunction<Bs...>::value 检查多个布尔类型特征的逻辑与 C++17 -
std::disjunction<Bs...>::value 检查多个布尔类型特征的逻辑或 C++17 -
std::negation<B>::value 检查布尔类型特征的逻辑非 C++17 -

 

///std::is_integral_v<T>的实现原理如下:
template<typename T>
inline constexpr bool is_integral_v = is_integral<T>::value;

//std::is_integral<T>::value的实现原理如下:
template <typename T>
struct is_integral {
    static constexpr bool value = false;
};

template <>
struct is_integral<int> {
    static constexpr bool value = true;
};

template <>
struct is_integral<long> {
    static constexpr bool value = true;
};

// 添加其他整型类型的特化...

  

posted @ 2024-04-11 14:52  fchy822  阅读(4)  评论(0编辑  收藏  举报