带有不同签名的std :: function的矢量 [英] Vector of std::function with different signatures

查看:129
本文介绍了带有不同签名的std :: function的矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些具有不同签名的回调函数。理想情况下,我想把这些在一个向量,并根据某些条件调用适当的。

I have a number of callback functions with different signatures. Ideally I would like to put these in a vector and call the appropriate one depending on certain conditions.

例如

void func1(const std::string& value);

void func2(const std::string& value, int min, int max);

const std::vector<std::function<void(std::string)>> functions
{
    func1,
    func2,
};

我意识到上述是不可能的,但我想知道是否有任何替代方案,我应该考虑。我还没有找到任何,我已经尝试了std :: bind,但没有管理达到我想要的。

I realise the above isn't possible but I wonder if there are any alternatives I should consider. I haven't been able to find any yet and I've experimented with std::bind but not managed to achieve what I want.

这样的事情可能吗?

推荐答案

您还没有说出您期望能够使用 func2 把它放在一个错误类型的向量。

You haven't said what you expect to be able to do with func2 after putting it in a vector with the wrong type.

如果你提前知道参数,你可以很容易地使用 std :: bind

You can easily use std::bind to put it in the vector if you know the arguments ahead of time:

const std::vector<std::function<void(std::string)>> functions
{
    func1,
    std::bind(func2, std::placeholders::_1, 5, 6)
};

现在 functions [1](foo)将调用 func2(foo,5,6),并且将传递 5 和<$ c $

Now functions[1]("foo") will call func2("foo", 5, 6), and will pass 5 and 6 to func2 every time.

这里是使用lambda的同样的东西。

Here's the same thing using a lambda instead of std::bind

const std::vector<std::function<void(std::string)>> functions
{
    func1,
    [=](const std::string& s){ func2(s, func2_arg1, func2_arg2); }
};

如果你还不知道参数,你可以将引用绑定到一些变量:

If you don't know the arguments yet, you can bind references to some variables:

int func2_arg1 = 5;
int func2_arg2 = 6;
const std::vector<std::function<void(std::string)>> functions
{
    func1,
    std::bind(func2, std::placeholders::_1, std::ref(func2_arg1), std::ref(func2_arg2))
};

现在 functions [1](foo)将调用 func2(foo,func2_arg1,func2_arg2),并且可以为整数分配新值以将不同的参数传递给 func2

Now functions[1]("foo") will call func2("foo", func2_arg1, func2_arg2), and you can assign new values to the integers to pass different arguments to func2.

使用lambda函数代替 std :: bind

And using a lambda function instead of std::bind

const std::vector<std::function<void(std::string)>> functions
{
    func1,
    [&](const std::string& s){ func2(s, func2_arg1, func2_arg2); }
};

这是非常丑陋的,因为你需要保留 int 变量,只要存在指向它们的可调用对象(闭包或绑定表达式)。

This is pretty ugly though, as you need to keep the int variables around for as long as the callable object (the closure or the bind expression) referring to them exists.

这篇关于带有不同签名的std :: function的矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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