我试图在std::tuple中存储不同数量的值,这些值稍后将用作调用匹配存储类型的函数指针的参数。

我创建了一个简化的例子来展示我正在努力解决的问题:

#include <iostream>
#include <tuple>

void f(int a, double b, void* c) {
  std::cout << a << ":" << b << ":" << c << std::endl;
}

template <typename ...Args>
struct save_it_for_later {
  std::tuple<Args...> params;
  void (*func)(Args...);

  void delayed_dispatch() {
     // How can I "unpack" params to call func?
     func(std::get<0>(params), std::get<1>(params), std::get<2>(params));
     // But I *really* don't want to write 20 versions of dispatch so I'd rather 
     // write something like:
     func(params...); // Not legal
  }
};

int main() {
  int a=666;
  double b = -1.234;
  void *c = NULL;

  save_it_for_later<int,double,void*> saved = {
                                 std::tuple<int,double,void*>(a,b,c), f};
  saved.delayed_dispatch();
}

通常,对于涉及std::tuple或可变参数模板的问题,我会编写另一个模板,如template <typename Head, typename…Tail>来逐个递归地计算所有类型,但我看不出调度函数调用的方法。

这样做的真正动机有些复杂,它主要只是一个学习练习。您可以假设我是通过契约从另一个接口传递元组的,因此不能更改,但希望将其解压缩到函数调用中是我的愿望。这就排除了使用std::bind来规避潜在问题的廉价方法。

使用std::tuple调度调用的干净方法是什么,或者实现存储/转发一些值和函数指针直到任意未来点的相同净结果的替代更好的方法是什么?


当前回答

这是一个c++ 14的解决方案。

template <typename ...Args>
struct save_it_for_later
{
  std::tuple<Args...> params;
  void (*func)(Args...);

  template<std::size_t ...I>
  void call_func(std::index_sequence<I...>)
  { func(std::get<I>(params)...); }
  void delayed_dispatch()
  { call_func(std::index_sequence_for<Args...>{}); }
};

这仍然需要一个辅助函数(call_func)。由于这是一种常见的习惯用法,也许标准应该直接支持它作为std::调用和可能的实现

// helper class
template<typename R, template<typename...> class Params, typename... Args, std::size_t... I>
R call_helper(std::function<R(Args...)> const&func, Params<Args...> const&params, std::index_sequence<I...>)
{ return func(std::get<I>(params)...); }

// "return func(params...)"
template<typename R, template<typename...> class Params, typename... Args>
R call(std::function<R(Args...)> const&func, Params<Args...> const&params)
{ return call_helper(func,params,std::index_sequence_for<Args...>{}); }

然后我们的延迟调度就变成了

template <typename ...Args>
struct save_it_for_later
{
  std::tuple<Args...> params;
  std::function<void(Args...)> func;
  void delayed_dispatch()
  { std::call(func,params); }
};

其他回答

这是一个c++ 14的解决方案。

template <typename ...Args>
struct save_it_for_later
{
  std::tuple<Args...> params;
  void (*func)(Args...);

  template<std::size_t ...I>
  void call_func(std::index_sequence<I...>)
  { func(std::get<I>(params)...); }
  void delayed_dispatch()
  { call_func(std::index_sequence_for<Args...>{}); }
};

这仍然需要一个辅助函数(call_func)。由于这是一种常见的习惯用法,也许标准应该直接支持它作为std::调用和可能的实现

// helper class
template<typename R, template<typename...> class Params, typename... Args, std::size_t... I>
R call_helper(std::function<R(Args...)> const&func, Params<Args...> const&params, std::index_sequence<I...>)
{ return func(std::get<I>(params)...); }

// "return func(params...)"
template<typename R, template<typename...> class Params, typename... Args>
R call(std::function<R(Args...)> const&func, Params<Args...> const&params)
{ return call_helper(func,params,std::index_sequence_for<Args...>{}); }

然后我们的延迟调度就变成了

template <typename ...Args>
struct save_it_for_later
{
  std::tuple<Args...> params;
  std::function<void(Args...)> func;
  void delayed_dispatch()
  { std::call(func,params); }
};

实现这一点有点复杂(尽管这是可能的)。我建议您使用一个已经实现了这一点的库,即Boost。融合(调用函数)。作为奖励,Boost Fusion也可以与c++ 03编译器一起工作。

Johannes使用c++ 14 std::index_sequence(和函数返回类型作为模板参数RetT)的解决方案的变化:

template <typename RetT, typename ...Args>
struct save_it_for_later
{
    RetT (*func)(Args...);
    std::tuple<Args...> params;

    save_it_for_later(RetT (*f)(Args...), std::tuple<Args...> par) : func { f }, params { par } {}

    RetT delayed_dispatch()
    {
        return callFunc(std::index_sequence_for<Args...>{});
    }

    template<std::size_t... Is>
    RetT callFunc(std::index_sequence<Is...>)
    {
        return func(std::get<Is>(params) ...);
    }
};

double foo(int x, float y, double z)
{
  return x + y + z;
}

int testTuple(void)
{
  std::tuple<int, float, double> t = std::make_tuple(1, 1.2, 5);
  save_it_for_later<double, int, float, double> saved (&foo, t);
  cout << saved.delayed_dispatch() << endl;
  return 0;
}

您需要构建一个包含数字的参数包并解压缩它们

template<int ...>
struct seq { };

template<int N, int ...S>
struct gens : gens<N-1, N-1, S...> { };

template<int ...S>
struct gens<0, S...> {
  typedef seq<S...> type;
};


// ...
  void delayed_dispatch() {
     callFunc(typename gens<sizeof...(Args)>::type());
  }

  template<int ...S>
  void callFunc(seq<S...>) {
     func(std::get<S>(params) ...);
  }
// ...

a lot of answers have been provided but I found them too complicated and not very natural. I did it another way, without using sizeof or counters. I used my own simple structure (ParameterPack) for parameters to access the tail of parameters instead of a tuple. Then, I appended all the parameters from my structure into function parameters, and finnally, when no more parameters were to be unpacked, I run the function. Here is the code in C++11, I agree that there is more code than in others answers, but I found it more understandable.

template <class ...Args>
struct PackParameters;

template <>
struct PackParameters <>
{
    PackParameters() = default;
};

template <class T, class ...Args>
struct PackParameters <T, Args...>
{
    PackParameters ( T firstElem, Args... args ) : value ( firstElem ), 
    rest ( args... ) {}

    T value;
    PackParameters<Args...> rest;
};

template <class ...Args>
struct RunFunction;

template <class T, class ...Args>
struct RunFunction<T, Args...>
{
    template <class Function>
    static void Run ( Function f, const PackParameters<T, Args...>& args );

    template <class Function, class... AccumulatedArgs>
    static void RunChild ( 
                          Function f, 
                          const PackParameters<T, Args...>& remainingParams, 
                          AccumulatedArgs... args 
                         );
};

template <class T, class ...Args>
template <class Function>
void RunFunction<T, Args...>::Run ( 
                                   Function f, 
                                   const PackParameters<T, Args...>& remainingParams 
                                  )
{
    RunFunction<Args...>::template RunChild ( f, remainingParams.rest,
                                              remainingParams.value );
}

template <class T, class ...Args>
template<class Function, class ...AccumulatedArgs>
void RunFunction<T, Args...>::RunChild ( Function f, 
                                         const PackParameters<T, Args...>& remainingParams, 
                                         AccumulatedArgs... args )
{
    RunFunction<Args...>:: template RunChild ( f, remainingParams.rest,
                                               args..., remainingParams.value );
}


template <>
struct RunFunction<>
{
    template <class Function, class... AccumulatedArgs>
    static void RunChild ( Function f, PackParameters<>, AccumulatedArgs... args )
    {
        f ( args... );
    }

    template <class Function>
    static void Run ( Function f, PackParameters<> )
    {
        f ();
    }
};

struct Toto
{
    std::string k = "I am toto";
};

void f ( int i, Toto t, float b, std::string introMessage )
{
    float res = i * b;

    std::cerr << introMessage << " " << res << std::endl;
    std::cerr << "Toto " << t.k << std::endl;
}

int main(){
    Toto t;
    PackParameters<int, Toto, float, std::string> pack ( 3, t, 4.0, " 3 * 4 =" );

    RunFunction<int, Toto, float, std::string>::Run ( f, pack );
    return 0;
}