在运行时使用函数转换类型列表

Cha*_*ton 6 c++ templates variadic-templates c++11

我有一个类型列表.我想创建一个元组,其结果是在该列表中的每个类型上调用一个函数,然后将其用作另一个仿函数的参数.所以像这样:

template<typename F>
struct function_traits;

template<typename T, typename R, typename... Args>
struct function_traits<R(T::*)(Args...) const> {
    using return_type = R;
    using param_types = std::tuple<Args...>;
};

template<typename T> struct function_traits : public
function_traits<decltype(&T::operator())> {};

template <typename T>
T* get_arg(int id)
{
    // Actual implementation omitted. Uses the id parameter to 
    // do a lookup into a table and return an existing instance 
    // of type T.
    return new T();
}

template <typename Func>
void call_func(Func&& func, int id)
{
    using param_types = function_traits<Func>::param_types>;

    func(*get_arg<param_types>(id)...); // <--- Problem is this line
}

call_func([](int& a, char& b) { }, 3);
Run Code Online (Sandbox Code Playgroud)

问题是func(*get_arg<param_types>(id)...);实际上没有编译,因为param_types是一个元组而不是参数包.编译器生成此错误:"没有可用于展开的参数包".我希望发生的是将该行扩展为:

func(*get_arg<int>(id), *get_arg<char>(id));
Run Code Online (Sandbox Code Playgroud)

并且可以为任何数量的论点工作.有没有办法得到这个结果?

这个问题看起来很相似,但本身并没有解决我的问题:"解包"一个元组来调用匹配的函数指针.我有一个类型列表,从中我想生成一个值列表,用作函数参数.如果我有值列表,我可以扩展它们并调用该问题中概述的函数,但我没有.

max*_*x66 2

不确定那是你想要的。

我不知道如何在内部扩展call_func()参数包,params_type但是,如果您能够使用辅助结构和 C++14 编译器...

我准备了以下支持返回类型的示例。

#include <tuple>

template<typename F>
struct function_traits;

template<typename T, typename R, typename... Args>
struct function_traits<R(T::*)(Args...) const> {
    using return_type = R;
    using param_types = std::tuple<Args...>;
};

template<typename T> struct function_traits : public
function_traits<decltype(&T::operator())> {};

template <typename T, typename ... Args>
T get_arg (std::tuple<Args...> const & tpl)
 { return std::get<typename std::decay<T>::type>(tpl); } 

template <typename ...>
struct call_func_helper;

template <typename Func, typename Ret, typename ... Args>
struct call_func_helper<Func, Ret, std::tuple<Args...>>
 {
   template <typename T, typename R = Ret>
      static typename std::enable_if<false == std::is_same<void, R>::value, R>::type
                fn (Func const & func, T const & t)
       { return func(get_arg<Args>(t)...); }

   template <typename T, typename R = Ret>
      static typename std::enable_if<true == std::is_same<void, R>::value, R>::type
                fn (Func const & func, T const & t)
       { func(get_arg<Args>(t)...); }
 };

template <typename Func,
          typename T,
          typename R = typename function_traits<Func>::return_type>
R call_func (Func const & func, T const & id)
 {
    using param_types = typename function_traits<Func>::param_types;

    return call_func_helper<Func, R, param_types>::fn(func, id);
 }

int main()
 {
   call_func([](int const & a, char const & b) { }, std::make_tuple(3, '6'));

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。