“拆包”一个元组调用匹配函数指针 [英] "unpacking" a tuple to call a matching function pointer

查看:196
本文介绍了“拆包”一个元组调用匹配函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 std :: tuple 中存储不同数量的值,稍后将用作调用函数指针的参数,

I'm trying to store in a std::tuple a varying number of values, which will later be used as arguments for a call to a function pointer which matches the stored types.

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

I've created a simplified example showing the problem I'm struggling to solve:

#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> 逐个递归地评估所有类型,但我看不到这样做的方式调度一个函数调用。

Normally for problems involving std::tuple or variadic templates I'd write another template like template <typename Head, typename ...Tail> to recursively evaluate all of the types one by one, but I can't see a way of doing that for dispatching a function call.

这真的动机有点更复杂,它大多只是一个学习练习。你可以假设我通过合同从另一个接口传递元组,所以不能改变,但是打开它到函数调用的愿望是我的。这排除了使用 std :: bind 作为避开潜在问题的便宜方式。

The real motivation for this is somewhat more complex and it's mostly just a learning exercise anyway. You can assume that I'm handed the tuple by contract from another interface, so can't be changed but that the desire to unpack it into a function call is mine. This rules out using std::bind as a cheap way to sidestep the underlying problem.

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

What's a clean way of dispatching the call using the std::tuple, or an alternative better way of achieving the same net result of storing/forwarding some values and a function pointer until an arbitrary future point?

推荐答案

您需要构建一个数字参数包并将其解包。

You need to build a parameter pack of numbers and unpack them

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

这篇关于“拆包”一个元组调用匹配函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆