c++:数据类型的推断type_traits

//推断左值右值引用
void main()
{
	int i(10);//i是左值  有内存实体
	int &ri(i);
	int &&rri(i + 5);//右值引用
	cout << is_lvalue_reference<decltype(i)>::value << endl;//是左值不是引用 输出0
	cout << is_lvalue_reference<decltype(ri)>::value << endl;//是左值引用输出1
	cout << is_lvalue_reference<decltype(rri)>::value << endl;//是右值引用输出0
	cin.get();
}


//此处的 decltype 引用常量都能够获取
//检測是否是数组
void main()
{
	int a[5];
	int *p = a;
	cout << is_array<decltype(a)>::value << endl;//数组输出1
	cout << is_array<decltype(p)>::value << endl;//非数组输出0
	cin.get();
}



void main()
{
	int num = 123;
	double db = 23;
	cout << is_integral<decltype(num)>::value << endl;//推断数据类型  int  1
	cout << is_integral<decltype(db)>::value << endl;//不是int型  0

	string str1;//cpp中的string也是个类
	cout << is_class<string>::value << endl;//1
	cout << is_class<decltype(str1)>::value << endl;//1
	cin.get();
}



template<class T1,class T2>
void same(const T1 &t1, const T2&t2)
{
	cout << is_same<T1, T2>::value << endl;//判定类型是否相等
}
//推断模板的数据类型
void main()
{
	same(12, 34);//一样的数据类型输出  1
	same(12, 34.23);//不一样输出   0
	same('A', 34);//0
	same("sdjbjabf", 34);//0
	cin.get();
}



template<class T1, class T2>
void same2(const T1 &t1, const T2&t2)
{
	//cout << typeid(T1).name() << is_integral(t1) << endl;//error
	cout << typeid(T1).name() << "    " << typeid(t1).name() << "    " << is_integral<T1>::value << endl;
	cout << is_same<T1, T2>::value << endl;
}
//推断模板的数据类型
void main()
{
	same2(12, 34);
	same2(12, 34.23);
	same2('A', 34);
	same2("sdjbjabf", 34);
	cin.get();
}




int add()
{
	return 0;
}
double check()
{
	return 0;
}
class A
{};
class B
{};
template<typename T1,typename T2>
void check_type(const T1 &t1, const T2 &t2,typename enable_if<is_same<T1,T2>::value>::type*p=nullptr)
{
	cout << t1<<"	"<<t2 <<":类型同样"<< endl;
}
template<typename T1, typename T2>
void check_type(const T1 &t1, const T2 &t2, typename enable_if<!is_same<T1, T2>::value>::type*p = nullptr)
{
	cout << t1 << "	" << t2 << ":类型不同样" << endl;
}
//模板与type推断类型的异同   依据參数类型自己主动选择模板
void main()
{
	check_type(12, 34);
	check_type(12.34, 0.12);
	check_type(12, 34.0);

	check_type(12, (float)34);
	check_type((int)12.34, (int)0.12);

	check_type('A','
');
	check_type("1234", "abcd");

	check_type(add, check);
	A a;
	B b;
	check_type(&a, &b);
	cin.get();
}

原文地址:https://www.cnblogs.com/wzzkaifa/p/7020087.html