带有矢量元素的函数调用的通用模板 [英] Generic template for calling function with vector elements

查看:67
本文介绍了带有矢量元素的函数调用的通用模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个来自矢量的参数来调用一个函数。仅此一项当然很容易,但是我想编写一个通用包装器来为我完成分配。稍后它也应该从诸如boost :: variant之类的通用类型进行转换,但是我认为在解决此问题之后我就可以解决。

I would like to call a function with the arguments coming from a vector. This alone is certainly very easy, but I would like to write a generic wrapper that does the assignment for me. Later it should also do the conversion from a generic type like boost::variant, but I think I can handle that after this problem is solved.

这是我的第一次尝试:

#include <iostream>
#include <functional>
#include <vector>

using namespace std;

void foo(int a, int b)
{
  cout << a*10+b << endl;
}

template<class... Args>
void callByVector(std::function<void(Args...)> f, vector<int>& arguments)
{
  int i = 0;
  f(static_cast<Args>(arguments[i++])...);
}

int main()
{
  vector<int> arguments;
  arguments.push_back(2);
  arguments.push_back(3);

  callByVector(std::function<void(int,int)>(foo),arguments);
}

它可以工作,但是您可能会猜到增量的执行顺序没有定义。
因此,总的结果可能是23或32(我可以使用不同的编译器来确认)。

It works, but as you might guess, the order of execution of the increments is not defined. Therefore, the overall result can be 23 or 32 (I can confirm that with different compilers).

任何想法还是我必须忘记这一点?

Any ideas or do I have to forget about that?

问候,
Florian

Greetings, Florian

推荐答案

您可以使用为此目的的索引。给定此编译时整数序列生成器:

You can use indices for that purpose. Given this generator of compile-time integer sequences:

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

template<int N, int... Is>
struct gen_seq : gen_seq<N - 1, N - 1, Is...> { };

template<int... Is>
struct gen_seq<0, Is...> : seq<Is...> { };

您可以让原始函数将工作委托给带有附加参数的帮助函数,该辅助函数允许推导整数序列。参数包扩展将完成其余工作:

You can let your original function delegate the work to a helper function called with an additional argument that allows deducing the sequence of integers. Argument pack expansion would do the rest:

template<class... Args, int... Is>
void callByVector(
    std::function<void(Args...)> f, vector<int>& arguments, seq<Is...>)
{
  f(arguments[Is]...);
}

template<class... Args>
void callByVector(std::function<void(Args...)> f, vector<int>& arguments)
{
  callByVector(f, arguments, gen_seq<sizeof...(Args)>());
}

这是 在线示例

这篇关于带有矢量元素的函数调用的通用模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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