c++类型萃取

1. 基本使用

获取去除指针类型,获取去除const类型 :

template<typename T>
struct remove_pointer {};

template<typename T>
struct remove_pointer<T*> {
    using type = T;
};

template<typename>
struct remove_const;

template<typename T>
struct remove_const<const T>
{
    using type = T;
};

int main()
{
    using type = remove_pointer<int*>::type;
    using type1 = remove_const<const int>::type;
}

2. 获取函数参数

获取函数返回值,获取函数参数:

bool foo(int) { return true; }

template<typename T>
struct func_traits;

template<typename Ret, typename Param>
struct func_traits<Ret(*)(Param)> {
    using ret_type = Ret;
    using ret_param = Param;
};

int main()
{
    auto ptr = &foo;
    using func_info = func_traits<decltype(ptr)>;
    using type = func_info::ret_type;
    using param = func_info::ret_param;
}

将鼠标停留type上可看到类型为bool,停留param上可看到类型为int

获取类中的函数参数:

struct Person {
    bool IsFemale(int) { return true; }
    float height;
};

template<typename Ret, typename Class, typename Param>
struct func_traits<Ret(Class::*)(Param)> {
    using ret_type = Ret;
    using ret_param = Param;
    using class_type = Class;
    static constexpr bool is_class = true;
};

int main()
{
    auto ptr = &Person::IsFemale;
    using class_info = func_traits<decltype(ptr)>;
    using type = class_info::ret_type;
    using param = class_info::ret_param;
    using classType = class_info::class_type;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值