How do I get the argument types of a function pointer in a variadic template class?

You can write function_traits class as shown below, to discover the argument types, return type, and 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

Leave a Comment

tech