C++基础-TypeTraits(进行类型的属性判断) 1.is_lvalue_reference(左值引用判断) 2.is_integral(整形判断) 3.is_class(基本类型判段) 4.is_same(判断类型一致) 5.enable_if(条件判断)

1.使用 is_lvalue_reference 进行左值引用判断, is_rvalue_reference(右值引用判断)

#include<iostream>
#include<type_traits>
#include<string>

int main1()
{
    int i(10);
    int & ri(i);
    int &&rri(i + 3);
    cout << is_lvalue_reference<decltype(i)>::value << std::endl;
    cout << is_lvalue_reference<decltype(ri)>::value << std::endl;
    cout << is_rvalue_reference<decltype(rri)>::value << std::endl;
    //判断左值引用还是右值引用
}

2. 使用is_array 判断是否是数组

int main2()
{
    int a[5];
    int *p = a;
    cout << is_array<decltype(a)>::value << endl;
    cout << is_array<decltype(p)>::value << endl;
    return 0;
}

3.使用is_integral判断是否是整形, is_class 判断是否是基本类型

int main3()
{
    int num = 10;
    double db = 20;
    string str1;
    cout << is_integral<decltype(num)>::value << endl;
    cout << is_integral<decltype(db)>::value << endl;
    cout << is_class<string>::value << endl;
    cout << is_class<decltype(str1)>::value << endl;
    //数据类型
    cin.get();
}

4.判断两个数据类型是否一致

#include<iostream>
#include<type_traits>
#include<string>
using namespace std;

template <class T1, class T2>
void same(const T1 &t1, const T2 &t2)
{
    cout << is_same<T1, T2>::value << endl; //判断类型是否相等
    cout << typeid(T1).name() << is_integral<T1>::value << endl;
}
int main1()
{
    same(1, 123);
    same(1, 123.1);
    same(3, "123");
    cin.get();
}

5.enable_if 来构造模板的匹配选项,如果类型匹配成功,执行一种操作,匹配失败执行另外一种操作

#include<iostream>
#include<type_traits>
#include<string>
using namespace std;

//typename enable_if<     is_same<T1, T2>::value   >::type     *p = nullptr 默认参数

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;
    cout << "类型相同" << 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;
    cout << "类型不相同" << endl;
}

int main()
{
    check_type(1, 10);
    check_type(1, 10.1);
    cin.get();
}
原文地址:https://www.cnblogs.com/my-love-is-python/p/15121426.html