我试图在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调度调用的干净方法是什么,或者实现存储/转发一些值和函数指针直到任意未来点的相同净结果的替代更好的方法是什么?


当前回答

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;
}

其他回答

c++ 14的解决方案。首先,一些实用工具样板:

template<std::size_t...Is>
auto index_over(std::index_sequence<Is...>){
  return [](auto&&f)->decltype(auto){
    return decltype(f)(f)( std::integral_constant<std::size_t, Is>{}... );
  };
}
template<std::size_t N>
auto index_upto(std::integral_constant<std::size_t, N> ={}){
  return index_over( std::make_index_sequence<N>{} );
}

这允许您使用一系列编译时整数调用lambda。

void delayed_dispatch() {
  auto indexer = index_upto<sizeof...(Args)>();
  indexer([&](auto...Is){
    func(std::get<Is>(params)...);
  });
}

做完了。

Index_upto和index_over允许您使用参数包,而无需生成新的外部重载。

当然,在c++17中

void delayed_dispatch() {
  std::apply( func, params );
}

现在,如果我们喜欢这样,在c++14中我们可以这样写:

namespace notstd {
  template<class T>
  constexpr auto tuple_size_v = std::tuple_size<T>::value;
  template<class F, class Tuple>
  decltype(auto) apply( F&& f, Tuple&& tup ) {
    auto indexer = index_upto<
      tuple_size_v<std::remove_reference_t<Tuple>>
    >();
    return indexer(
      [&](auto...Is)->decltype(auto) {
        return std::forward<F>(f)(
          std::get<Is>(std::forward<Tuple>(tup))...
        );
      }
    );
  }
}

相对简单,并且准备好发布更简洁的c++17语法。

void delayed_dispatch() {
  notstd::apply( func, params );
}

当你的编译器升级时,只要将notstd替换为STD, Bob就是你的叔叔。

在给出答案的基础上再思考一下这个问题,我发现了另一种解决同样问题的方法:

template <int N, int M, typename D>
struct call_or_recurse;

template <typename ...Types>
struct dispatcher {
  template <typename F, typename ...Args>
  static void impl(F f, const std::tuple<Types...>& params, Args... args) {
     call_or_recurse<sizeof...(Args), sizeof...(Types), dispatcher<Types...> >::call(f, params, args...);
  }
};

template <int N, int M, typename D>
struct call_or_recurse {
  // recurse again
  template <typename F, typename T, typename ...Args>
  static void call(F f, const T& t, Args... args) {
     D::template impl(f, t, std::get<M-(N+1)>(t), args...);
  }
};

template <int N, typename D>
struct call_or_recurse<N,N,D> {
  // do the call
  template <typename F, typename T, typename ...Args>
  static void call(F f, const T&, Args... args) {
     f(args...);
  }
};

这需要将delayed_dispatch()的实现更改为:

  void delayed_dispatch() {
     dispatcher<Args...>::impl(func, params);
  }

这是通过递归地将std::tuple转换为自己的参数包来实现的。需要Call_or_recurse作为专门化来终止使用实际调用的递归,实际调用只是解包完成的参数包。

我不确定这是否是一个“更好的”解决方案,但这是另一种思考和解决问题的方式。


作为另一个替代解决方案,你可以使用enable_if,形成一些可以说比我之前的解决方案更简单的东西:

#include <iostream>
#include <functional>
#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...);

  template <typename ...Actual>
  typename std::enable_if<sizeof...(Actual) != sizeof...(Args)>::type
  delayed_dispatch(Actual&& ...a) {
    delayed_dispatch(std::forward<Actual>(a)..., std::get<sizeof...(Actual)>(params));
  }

  void delayed_dispatch(Args ...args) {
    func(args...);
  }
};

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();
}

第一个重载只是从元组中再取一个参数,并将其放入参数包中。第二个重载接受一个匹配的参数包,然后进行真正的调用,只有在第二个重载可行的情况下才禁用第一个重载。

这是约翰内斯对林地问题的解决方案的完整汇编版本,希望对某些人有用。这是在Debian上用g++ 4.7的快照进行测试的。

###################
johannes.cc
###################
#include <tuple>
#include <iostream>
using std::cout;
using std::endl;

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; };

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

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

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

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

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
int main(void)
{
  gens<10> g;
  gens<10>::type s;
  std::tuple<int, float, double> t = std::make_tuple(1, 1.2, 5);
  save_it_for_later<int,float, double> saved = {t, foo};
  cout << saved.delayed_dispatch() << endl;
}
#pragma GCC diagnostic pop

可以使用下面的SConstruct文件

#####################
SConstruct
#####################
#!/usr/bin/python

env = Environment(CXX="g++-4.7", CXXFLAGS="-Wall -Werror -g -O3 -std=c++11")
env.Program(target="johannes", source=["johannes.cc"])

在我的机器上,这给出了

g++-4.7 -o johannes.o -c -Wall -Werror -g -O3 -std=c++11 johannes.cc
g++-4.7 -o johannes johannes.o

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

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) ...);
  }
// ...

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;
}