用元编程来判断STL类型

打印 上一主题 下一主题

主题 934|帖子 934|积分 2802

  在此之前,先来回顾元编程当中的一个重要概念。
  1. template<typename _Tp, _Tp __v>
  2.     struct integral_constant
  3.     {
  4.       static constexpr _Tp                  value = __v;
  5.       typedef _Tp                           value_type;
  6.       typedef integral_constant<_Tp, __v>   type;
  7.       constexpr operator value_type() const noexcept { return value; }
  8. #if __cplusplus > 201103L
  9. #define __cpp_lib_integral_constant_callable 201304L
  10.       constexpr value_type operator()() const noexcept { return value; }
  11. #endif
  12.     };
  13.   /// The type used as a compile-time boolean with true value.
  14.   using true_type =  integral_constant<bool, true>;
  15.   /// The type used as a compile-time boolean with false value.
  16.   using false_type = integral_constant<bool, false>;
复制代码
  std::true_type和std::false_type其实就是std::integral_constant传入模板特定参数的情形,注意到integral_constant结构体当中的value_type,顾名思义指的是值的类型,对应到std::true_type和std::false_type就是true和false。
  先尝试着来写一个对std::vector的判断。
[code]// vectortemplate struct is_vector : std::false_type{};template struct is_vector : std::true_type{};template bool is_vector_v = is_vector::value;int main() {    std::vector v1;    std::vector v2;    std::vector v3;        std::cout
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

去皮卡多

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表