在JIT编译时期进行类型检查

#include <iostream>
#include <list>
#include <vector>
using std::list;
#include <map>

template <typename T>
using vector = std::vector<T>;

#define DEF_IS(check_type, return_type) \
    template<class T> \
    typename std::enable_if<std::is_same<T, check_type>::value, return_type>::type

#define CHECK_IS_1(check_type) \
    template<typename T> struct is_##check_type : public std::false_type {}; \
    template<typename T> \
    struct is_##check_type<check_type<T>> : public std::true_type {};

CHECK_IS_1(vector);

#define DEF_IS_1(check_type, return_type) \
template<class T> \
typename std::enable_if<is_##check_type<T>::value, return_type>::type



template <typename T, typename V>
using map =  std::map<T,V>;

#define CHECK_IS_2(check_type) \
template<typename T> struct is_##check_type : public std::false_type {}; \
template<typename T, typename V> \
struct is_##check_type<check_type<T,V>> : public std::true_type {};

CHECK_IS_2(map)

#define DEF_IS_2(check_type, return_type) \
    template<class T> \
    typename std::enable_if<is_##check_type<T>::value, return_type>::type


// 使用上面的宏,在JIT编译时期进行类型检查

DEF_IS(bool , std::string) check_func0(){
    return "12";
}

DEF_IS_1(vector, bool) check_func1(std::string value) {
    return true;
}

DEF_IS_2(map, bool) check_func2(std::string value) {
    return true;
}

int main() {
    std::string value0 = check_func0<bool>();
    // 下面不能编译通过
    // std::string value0 = check_func0<int>();
    // 只有 vector<T> 拥有函数
    bool value = check_func1<vector<int>>("hello");
    bool value2 = check_func2<map<int, int>>("hello");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝鲸123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值