2013-03-07 177 views
4

因此,我給出了一個std::tuple<T...>,我想創建一個接受T...的函數指針,目前這是我所得到的;將std :: tuple <T...>轉換爲T

template<typename... Arguments> 
using FunctionPointer = void (*)(Arguments...); 

using FunctionPtr = FunctionPointer<typename std::tuple_element<0, V>::type, 
            typename std::tuple_element<1, V>::type, 
            typename std::tuple_element<2, V>::type>; 

不過,我似乎無法找到一個方法來做到這一點,沒有從0, ..., tuple_size<V>::value手動輸入每一個指標。 FunctionPtr被定義在一個上下文中,其中V=std::tuple<T...>(也已經有一個可變模板(因此我不能直接通過T...))

我想我需要生成一些索引列表,並做一些黑魔法..

+0

http://stackoverflow.com/questions/7858817/unpacking-a-tuple-to-call-a-matching-function-pointer – Morwenn 2013-03-07 11:31:48

+0

@Morwenn:那不需要我添加另一個可變參數模板嗎? – Skeen 2013-03-07 11:33:47

回答

5

這裏是一個可能的解決方案:

#include <tuple> 

// This is what you already have... 
template<typename... Arguments> 
using FunctionPointer = void (*)(Arguments...); 

// Some new machinery the end user does not need to no about 
namespace detail 
{ 
    template<typename> 
    struct from_tuple { }; 

    template<typename... Ts> 
    struct from_tuple<std::tuple<Ts...>> 
    { 
     using FunctionPtr = FunctionPointer<Ts...>; 
    }; 
} 

//================================================================= 
// This is how your original alias template ends up being rewritten 
//================================================================= 
template<typename T> 
using FunctionPtr = typename detail::from_tuple<T>::FunctionPtr; 

這裏是你將如何使用它:

// Some function to test if the alias template works correctly 
void foo(int, double, bool) { } 

int main() 
{ 
    // Given a tuple type... 
    using my_tuple = std::tuple<int, double, bool>; 

    // Retrieve the associated function pointer type... 
    using my_fxn_ptr = FunctionPtr<my_tuple>; // <== This should be what you want 

    // And verify the function pointer type is correct! 
    my_fxn_ptr ptr = &foo; 
} 
+0

令人驚歎! - 我一直在盜用它已經有一段時間了,你只需要一眨眼就修好它! - 看來我仍然需要用元組和模板模板進行很多練習;) – Skeen 2013-03-07 11:42:21

+0

@Skeen:這很正常,需要一段時間才能掌握它 – 2013-03-07 11:43:21

+0

接受你的答案。 – Skeen 2013-03-07 11:48:25

5

一個簡單的特質英里GHT做的伎倆:

#include <tuple> 

template <typename> struct tuple_to_function; 

template <typename ...Args> 
struct tuple_to_function<std::tuple<Args...>> 
{ 
    typedef void (*type)(Args...); 
}; 

用法:

typedef std::tuple<Foo, Bar, int> myTuple; 

tuple_to_function<myTuple>::type fp; // is a void (*)(Foo, Bar, int) 
相關問題