How to get function pointer argument types in a variational pattern class?

This is a continuation of this problem: A generic functor for functions with any argument list

I have this functor class (for the full code, see the link above):

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...); } }; 

In operator (), I can easily access args ... with a recursive peeling function, as described here http://www2.research.att.com/~bs/C++0xFAQ.html#variadic-templates

My problem: I want to access the argument types f, i.e. ARGS ..., in the constructor. Obviously, I canโ€™t access the values โ€‹โ€‹because they are not there yet, but the list of argument types is somehow shaded in f, right?

+23
c ++ c ++ 11 functor function-pointers variadic-templates
source share
1 answer

You can write the function_traits class as shown below to find out the types of arguments, the type of the return number, and the number of arguments:

 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; }; }; 

Test code:

 struct R{}; struct A{}; struct B{}; int main() { 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; } 

Demo: http://ideone.com/YeN29

+48
source share

All Articles