Accessing Argument Types in a Variadic Template Class for Function Pointers
In an effort to create a generic functor for functions with any argument list, a developer seeks to extract the argument types of a function pointer within the class constructor.
Consider the following functor class:
<code class="cpp">template<typename... ARGS> class Foo { private: 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>
To access the argument types within the constructor, the developer employs a technique of "peeling" the argument list recursively, as outlined by Stroustrup in his C 11 FAQ. However, the argument types are not readily accessible from the function pointer f.
By employing a function_traits class, it becomes possible to discover the argument types, return type, and the number of arguments associated with a function pointer.
<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>
Leveraging this function_traits class, the developer can now retrieve the argument types within the functor class constructor:
<code class="cpp">template<typename... ARGS> class Foo { private: std::function<void(ARGS...)> m_f; std::tuple<typename function_traits<decltype(m_f)>::arg<0>::type...> m_arg_types; public: Foo(std::function<void(ARGS...)> f) : m_f(f), m_arg_types(std::make_tuple(typename function_traits<decltype(m_f)>::arg<0>::type()...)) {} void operator()(ARGS... args) const { m_f(args...); } };</code>
The above is the detailed content of How can I access argument types from a function pointer within a variadic template class in C ?. For more information, please follow other related articles on the PHP Chinese website!