type trait: 提供一种处理type属性的办法;它是一个template,可在编译期间根据一个或多个模板实参产生一个type或value;
定义与头文件<type_traits>中;所有的类型判断工具: (1) 用来检验类型性质的Trait
(2).用来检验class类型的Trait
说明:
bool和所有的character类型(char,char16_t,char32_t,wchar_t)都被视为整数类型,std::nullptr_t被视为基础数据类型;一个指向“const类型”的非常量pointer或者reference,并不是一个常量,尽管内含常量元素的寻常array是一个常量;例子:
is_const<int>::value //false is_const<int* const> :: value //true ,不能修改指针的地址 is_const<const int*>:: value //false ,指向常量的指针,可以修改地址 is_const<int[]>::value //false is_const<const int[]>::value //true(3).用以检验类型关系的Trait
说明: 1. is_assignable<>的第一个类型若是个nonclass类型,永远会获得false_type,对于class类型,用其寻常类型作为第一个参数可以;
例子:
is_assignable<int,int>::value //false is_assignable<int&,int>::value //true is_assignable<int&,void*>::value //false is_assignable<string,const char*>::value //true用is_constructible<>:
is_constructible<int>::value //true is_constructible<int,int>::value //true is_constructible<int ,void*>::value //false(4)。类型修饰符 允许改变类型,前提是该属性未存在,或者移除一个已存在的属性
//添加 typedef int T; add_cosnt<T> ::type //const int add_pointer<T>::type //int* //移除 typeder int* T; remove_pointer<T>::type //int(5).其他Type Trait
对于一个给定的类型T,这个类提供了两个函数:
ref(): 把T隐式转换为 int&cref() : 把T隐式转换为 const int& 例子: template<typename T> void foo(T val); //经过调用: int x; foo(std::ref(x)); //T变成了int&, 而进过调用: int x; foo(std::cref(x)); //T变成了const int&这个特性被运用与各个地方:
make_pair(): 创建一个pair<> 引用 make_tuple() : 创建一个tuple<>引用 Binder: 用于绑定(bind)引用 Thread: 以by reference形式传递实参【注意】:reference_wrapper可以使用引用类型作为最高级对象: 例如:
vector<Myclass&> cool; //error vector<reference_wrapper<Myclass> > cool; //ok例子:
void func(int x, int y); vector<function<void(int ,int)>> task; task.push_back(func); task.push_back([](int x, int y ){...});//lambda函数 //调用函数 for(function<void(int,int)> f: task) { f(33,66); } //使用member function class C{ public: void memfunc(int x, in y)const; }; function<void(const C&,int,int)> mf; mf = &C::memfunc; mf(C(),32,22);【注意:】执行一个函数调用:但是没有目标可以调用,就会抛出std::bad_function_call异常 例子:
function<void(int,int)> f; //空对象 f(33,33);//throw bad_function_call