萃取(trait)技术与策略(policy)技术当中的值萃取(value traits)

一:值萃取(value traits)

固定萃取:给进来一个类型,萃取出一个类型
值萃取思想:从一个类型当中萃取出一个值。

二:常规例程演示

在这里插入代码片

三:判断是否为void类型范例演示

#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <deque>
#include <type_traits>
#include <boost/type_index.hpp>
using namespace std;
int main()
{
    /*is_void类模板:判断某个类型是否是void类型。
    */
    cout << "int是void类型吗?" << std::is_void<int>::value << endl; //0
    cout << "void是void类型吗?" << std::is_void<void>::value << endl; //1
    return 0;
}

实现一个类似的功能。

#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <deque>
#include <type_traits>
#include <boost/type_index.hpp>
using namespace std;
template <typename T> 
struct voidvaluetraits
{
    static const bool value = false;
};
template <>
struct voidvaluetraits<void>
{
    static const bool value = true;
};
int main()
{
    cout << "int是void类型吗?" << voidvaluetraits<int>::value << endl; //0
    cout << "void是void类型吗?" << voidvaluetraits<void>::value << endl; //1
    return 0;
}

在这里插入图片描述
四:判断两个类型是否相同

#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <deque>
#include <type_traits>
#include <boost/type_index.hpp>
using namespace std;

int main()
{
    /*is_same类模板,用于判断两个类型是否相同
    */
    cout << is_same<int, const int>::value << endl; //0
    cout << is_same<int, int>::value << endl; //1
    return 0;
}

is_same类似实现:

#include <iostream>
#include <list>
#include <vector>
#include <map>
#include <deque>
#include <type_traits>
#include <boost/type_index.hpp>
using namespace std;
//泛化版本
template<typename T1, typename T2>
struct IsSameType
{
    static const bool value = false;
};
//特化版本
template<typename T1>
struct IsSameType<T1, T1>
{
    static const bool value = true;
};
//变量模板
template<typename T1, typename T2>
const bool IsSame_v = IsSameType<T1, T2>::value;
int main()
{
    cout << IsSameType<int, const int>::value << endl; //0
    cout << IsSameType<int, int>::value << endl; //1
    return 0;
}

当然,因为std::true_type和std::false_type里面有value,所以也可以这样写。

//泛化版本
template<typename T1, typename T2>
struct IsSameType : std::false_type
{		
};
 
//特化版本
template<typename T1>
struct IsSameType<T1, T1>:std::true_type
{		
};

//变量模板
template<typename T1, typename T2>
const bool IsSame_v = IsSameType<T1, T2>::value;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值