2012-01-28 13 views

Odpowiedz

42

myślę sam std::function nie przewiduje tej funkcji. Ale można go realizować siebie jako:

template<typename T> 
struct count_arg; 

template<typename R, typename ...Args> 
struct count_arg<std::function<R(Args...)>> 
{ 
    static const size_t value = sizeof...(Args); 
}; 

kod Test:

typedef std::function<int(int, int)> fun; 
std::cout << count_arg<fun>::value << std::endl; //should print 2 

Zobacz to: Online demo


Podobnie, można umieścić więcej funkcji do tego, jak:

template<typename T> 
struct function_traits;  //renamed it! 

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

Teraz można dostać każdy rodzaj argumentów, za pomocą const indeksu, jak:

std::cout << typeid(function_traits<fun>::arg<0>::type).name() << std::endl; 
std::cout << typeid(function_traits<fun>::arg<1>::type).name() << std::endl; 
std::cout << typeid(function_traits<fun>::arg<2>::type).name() << std::endl; 

Working demo

wypisuje zmasakrowane-name typów!

+5

+1: Wow staje się bardzo prosty, gdy masz szablony variadyczne działające O__O; – Klaim

+1

Dobre rozwiązanie ... Nie wiedziałem, że 'sizeof ... (Args)' jest poprawną składnią! Czy 'sizeof()' ma specjalne znaczenie dla 'Args'? Ponieważ ogólnie 'sizeof()' dotyczy tylko rozmiaru typu danych, a nie liczby elementów. – iammilind

+4

@iammilind: 'sizeof ... (T)' to specjalna składnia pozwalająca uzyskać rozmiar pakietu parametrów 'T'. Nie ma to nic wspólnego z 'sizeof (T)' (§5.3.3/5, §14.5.3/7). – kennytm

Powiązane problemy