前言:

#include <type_traits>

type_traits 又叫类型萃取,是一个在编译阶段用于进行 类型判断/类型变更 的库,在c++11中引入。因为其工作阶段是在编译阶段,因此被大量应用在模板编程中,同时也可以结合 constexpr 这种在编译阶段就进行计算的语句进行编译阶段的运算。

类型判断:

判断模板类型是不是class类型

template<typename T>
void function(T){
  if(std::is_class(T)){
    printf("T is class type");
  }
}

判断两个模板类型是否相同

template<typename T,typename U>
void function(T,U){
  if(std::is_same(T,U)){
    printf("T and U is same type");
  }
}

类型变更:

移除/添加const限制

template<typename T>
void removeConst(T t){
  std::remove_const<T>(t);
}

template<typename T>
void removeConst(T t){
  std::add_const<T>(t);
}

更多功能参考:

Standard library header <type_traits> (C++11) - cppreference.com