Generic functors are useful classes that provide a convenient way to handle functions with varying argument lists. However, accessing the argument types of function pointers within these classes can be a challenge.
Consider the following functor class:
<code class="cpp">template <typename... ARGS> class Foo { std::function<void(ARGS...)> m_f; public: Foo(std::function<void(ARGS...)> f) : m_f(f) {} void operator()(ARGS... args) const { m_f(args...); } };</code>
While you can easily access the args... in the operator() method using a recursive "peeling" function, obtaining the argument types in the constructor is more complex.
To address this, you can implement a function_traits class:
<code class="cpp">template<typename T> struct function_traits; template<typename R, typename ...Args> struct function_traits<std::function<R(Args...)>> { static const size_t nargs = sizeof...(Args); typedef R result_type; template<size_t i> struct arg { typedef typename std::tuple_element<i, std::tuple<Args...>>::type type; }; };</code>
With this class, you can determine the argument types, return type, and number of arguments of a function pointer.
The following code demonstrates the functionality:
<code class="cpp">struct R {}; struct A {}; struct B {}; void main() { typedef std::function<R(A, B)> fun; cout << std::is_same<R, function_traits<fun>::result_type>::value << endl; cout << std::is_same<A, function_traits<fun>::arg<0>::type>::value << endl; cout << std::is_same<B, function_traits<fun>::arg<1>::type>::value << endl; }</code>
The above is the detailed content of How to Retrieve Argument Types of Function Pointers in Variadic Template Classes?. For more information, please follow other related articles on the PHP Chinese website!