2013-03-07 97 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) 
相关问题