function_traits.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #ifndef SRC_UTIL_FUNCTION_TRAITS_H_
  2. #define SRC_UTIL_FUNCTION_TRAITS_H_
  3. #include <tuple>
  4. using namespace std;
  5. namespace toolkit {
  6. template<typename T>
  7. struct function_traits;
  8. //普通函数
  9. template<typename Ret, typename... Args>
  10. struct function_traits<Ret(Args...)>
  11. {
  12. public:
  13. enum { arity = sizeof...(Args) };
  14. typedef Ret function_type(Args...);
  15. typedef Ret return_type;
  16. using stl_function_type = std::function<function_type>;
  17. typedef Ret(*pointer)(Args...);
  18. template<size_t I>
  19. struct args
  20. {
  21. static_assert(I < arity, "index is out of range, index must less than sizeof Args");
  22. using type = typename std::tuple_element<I, std::tuple<Args...> >::type;
  23. };
  24. };
  25. //函数指针
  26. template<typename Ret, typename... Args>
  27. struct function_traits<Ret(*)(Args...)> : function_traits<Ret(Args...)>{};
  28. //std::function
  29. template <typename Ret, typename... Args>
  30. struct function_traits<std::function<Ret(Args...)>> : function_traits<Ret(Args...)>{};
  31. //member function
  32. #define FUNCTION_TRAITS(...) \
  33. template <typename ReturnType, typename ClassType, typename... Args>\
  34. struct function_traits<ReturnType(ClassType::*)(Args...) __VA_ARGS__> : function_traits<ReturnType(Args...)>{}; \
  35. FUNCTION_TRAITS()
  36. FUNCTION_TRAITS(const)
  37. FUNCTION_TRAITS(volatile)
  38. FUNCTION_TRAITS(const volatile)
  39. //函数对象
  40. template<typename Callable>
  41. struct function_traits : function_traits<decltype(&Callable::operator())>{};
  42. } /* namespace toolkit */
  43. #endif /* SRC_UTIL_FUNCTION_TRAITS_H_ */