2012-01-30 53 views
23

這是這個問題的追問:Generic functor for functions with any argument list如何在variadic模板類中獲取函數指針的參數類型?

我有這樣的函數子類(完整的代碼見上面的鏈接):

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

在運營商()我可以訪問ARGS ...輕鬆地與這裏描述的遞歸「剝皮」功能http://www2.research.att.com/~bs/C++0xFAQ.html#variadic-templates

我的問題是:我想在構造函數中訪問f的參數類型,即ARGS ...。顯然我無法訪問值,因爲目前還沒有值,但參數類型列表以某種方式在f中被埋沒,不是嗎?

回答

48

你可以寫function_traits類,如下圖所示,發現參數類型,返回類型和數量的參數:

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

測試代碼:

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

演示:http://ideone.com/YeN29

+0

謝謝@Nawaz,迄今爲止工作。儘管如此,我想從這個解決方案中提取出「魔術」並將其放入我的代碼中。我認爲typename std :: tuple_element > :: type是它發生的地方......我該怎麼做,而不必申報另一個struct – steffen 2012-01-30 15:03:36

+0

@steffen:在定義另一個結構體時是否有任何問題哪些可以在其他情況下使用?而且,將所有代碼放在一個類中並不是一個好主意。嘗試將代碼分成小工作單元。 – Nawaz 2012-01-30 15:11:00

+0

我明白你的觀點。最後一個問題是來自boost庫的這段代碼? function_traits聽起來很熟悉;) – steffen 2012-01-30 15:15:03

相關問題