Ske*_*een 4 c++ templates c++11 stdtuple
所以我给了一个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>;
Run Code Online (Sandbox Code Playgroud)
但是我似乎无法找到一种方法来做到这一点,而无需手动输入每个索引0, ..., tuple_size<V>::value.FunctionPtr是在上下文中定义的,其中V=std::tuple<T...>(也有一个可变参数模板(因此我不能直接传递T...))
我想我需要生成一些索引列表,并做一些黑魔法..
这是一个可能的解决方案:
#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;
Run Code Online (Sandbox Code Playgroud)
以下是您将如何使用它:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
一个简单的特征可能会成功:
#include <tuple>
template <typename> struct tuple_to_function;
template <typename ...Args>
struct tuple_to_function<std::tuple<Args...>>
{
typedef void (*type)(Args...);
};
Run Code Online (Sandbox Code Playgroud)
用法:
typedef std::tuple<Foo, Bar, int> myTuple;
tuple_to_function<myTuple>::type fp; // is a void (*)(Foo, Bar, int)
Run Code Online (Sandbox Code Playgroud)