01 类型萃取

类型萃取

指针萃取

template <typename T>
struct remove_pointer{};

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

template <typename T>
using remove_pointer_t = remove_pointer<T>::type;

const萃取

template <typename T>
struct remove_const{};

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

function萃取

normal function

template <typename Ret, typename... Args>
struct function_traits {};

template <typename Ret, typename... Args>
struct function_traits<Ret(*)(Args...)>
{
using return_type = Ret;
using args_type = std::tuple<Args...>;
}

void foo();
int main()
{
using foo_type = decltype(foo);
using foo_ret = function_traits<foo_type>::retrun_type;
using foo_args_type = function_traits<foo_type>::args_type;
}

class function&variable

struct Person
{
bool IsFemale() const;
bool IsFemaleNonConst();
};

template <typename Ret, typename Class, typename... Args>
struct class_function_traits{};

template <typename Ret, typename Class, typename... Args>
struct class_function_traits<Ret(Class::*)(Args...)>
{
using return_type = Ret;
using class_type = Class;
using args_type = std::tuple<Args...>;
}

template <typename Class, typename T>
struct class_variable_traits{};

template <typename Class, typename T>
struct class_variable_traits<T Class::*>
{
using class_type = Class;
using variable_type = T;
};

简单的Class类型信息萃取

宏魔法辅助工具

template <typename T>
struct TypeInfo{};

#define BEGIN_CLASS(T) \
template<> struct TypeInfo<T> {\
using type = T;

#define FUNCTIONS(...) using functions = std::tuple<__VA_ARGS__>;

#define VARIABLES(...) using variables = std::typle<__VA_ARGS__>;

#define END_CLASS() };

案例

struct Person
{
bool IsFemale() const;
bool IsFemaleNonConst();

int money;
};

BEGIN_CLASS(Person)
FUNCTIONS(class_function_traits<&Person::IsFemale>,
class_function_traits<&Person::IsFemaleNonConst>)
VARIABLES(class_variable_traits<&Person::money>)
END_CLASS()

int main()
{
using person_type = TypeInfo<Person>; //萃取出的person对应的info类
}