Home > Article > Backend Development > How to Retrieve Argument Types of a Function Pointer in a Variadic Template Class?
Retrieving Argument Types of a Function Pointer in a Variadic Template Class
In the previous issue, a generic functor class was created to handle functions with arbitrary argument lists. The issue at hand involves accessing the argument types of the function pointer within the constructor of this class.
To address this issue, you can utilize the function_traits class template:
<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>
This class provides the following functionality:
For example:
<code class="cpp">struct R{}; struct A{}; struct B{}; typedef std::function<R(A,B)> fun; std::cout << std::is_same<R, function_traits<fun>::result_type>::value << std::endl; std::cout << std::is_same<A, function_traits<fun>::arg<0>::type>::value << std::endl; std::cout << std::is_same<B, function_traits<fun>::arg<1>::type>::value << std::endl;</code>
Output:
1 1 1
This example demonstrates how to utilize function_traits to retrieve the argument types within the constructor of a variadic template class.
The above is the detailed content of How to Retrieve Argument Types of a Function Pointer in a Variadic Template Class?. For more information, please follow other related articles on the PHP Chinese website!