2012-01-28 82 views

回答

42

我覺得std::function本身並沒有提供該功能。但是你可以自己實現它:

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

測試代碼:

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

看到這個:Online demo


同樣,你可以將更多的功能集成到這一點,因爲:

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

現在你可以得到每個參數類型,使用常量指標,如:

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

它輸出類型的錯位名!

+5

+1:哇,它變得真的很簡單,一旦你有可變參數模板工作O__O; – Klaim 2012-01-28 11:39:21

+1

不錯的解決方案...我不知道,'sizeof ...(Args)'是一個合適的語法!是否,'sizeof()'對'Args'有特殊意義?因爲通常'sizeof()'只處理數據類型的大小,而不處理元素的數量。 – iammilind 2012-01-28 12:21:20

+4

@iammilind:'sizeof ...(T)'是獲取參數包'T'大小的特殊語法。它與sizeof(T)'(§5.3.3/ 5,§14.5.3/ 7)無關。 – kennytm 2012-01-28 12:34:43

相關問題