// type_traits中源码
template <class T, T val>
struct integral_constant
{
typedef integral_constant<T, val> type;
typedef T value_type;
static const T value = val;
};
// ture type
typedef integral_constant<bool, true> true_type;
// flase type
typedef integral_constant<bool, false> false_type;
#include
#include
using namespace std;
int main()
{
// 判断int和const int类型
std::cout << "int: " << std::is_const<int>::value << std::endl;
std::cout << "const int:" << std::is_const<const int>::value << std::endl;
// 判断类型是否相同
std::cout << std::is_same<int, int>::value << "\n";
std::cout << std::is_same<int, unsigned int>::value << "\n";
// 添加/移除const
std::cout << std::is_same<const int, add_const<int>::type>::value << std::endl;
std::cout << std::is_same<int, remove_const<const int>::type>::value << std::endl;
//添加引用
std::cout << std::is_same<int&, add_lvalue_reference<int>::type>::value << std::endl;
std::cout << std::is_same<int&&, add_rvalue_reference<int>::type>::value << std::endl;
// 取公共类型
typedef std::common_type<unsigned char, short, int>::type NumericType;
std::cout << std::is_same<int, NumericType>::value << std::endl;
return 0;
}
// 原型
template<bool B, class T, class F>
struct conditional;
// 例子
#include
#include
using namespace std;
int main()
{
typedef std::conditional<true, int , char>::type A;
typedef std::conditional<false, int, char>::type B;
}
// 例
typedef std::decay<int>::type Normal; // int
typedef std::decay<int&>::type Ref; // int
typedef std::decay<int&&>::type RefRef; // int
typedef std::decay<const int&>::type const; // int
typedef std::decay<int[2]>::type Array; // int*
typedef std::decay<int(int)>::type FunPtr; // int(*)(int) 函数指针
因此,利用std::decay可以方便的获得函数指针。
type_traits std::result_of元函数,用来获取可调用对象的返回类型。
typedef int(&fn_ref)(int);
typedef int(*fn_ptr)(int);
struct fn_class
{
int operator()(int i)
{
return i;
}
}
int main()
{
typedef std::result_of<fn_ref(int)>::type int_f; // int
typedef std::reuslt_of<fn_ptr(int)>::type int_s; // int
}
// 原型 ,在判断条件B为真时,函数才有效
template<bool B, class T = void> struct enable_if;
// 例
typename std::endable_if<std::is_arithmetic<T>::value, T>::type foo(T t)
{
return t;
}
auto numberic = foo(1); // 返回整数1
auto str = foo("test"); // 编译失败
// 例 相当于函数重载,通过enable_if和条件判断式,将入参分为两类(数字和非数字)
template<class T>
typename std::enable_if<std::is_arithmetic<T>::value, int>::type fool(T t)
{
cout<< t << endl;
return 0;
}
template<class T>
typename std::enable_if<!std::is_arithmetic<T>::value, int>::type fool(T& t) foo(T t)
{
cout << t << endl;
return 1;
}