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;
}