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


当前回答

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

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

其他回答

这是一个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); }
};

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就是你的叔叔。

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

这是约翰内斯对林地问题的解决方案的完整汇编版本,希望对某些人有用。这是在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