其他分享
首页 > 其他分享> > c – 具有不同签名的std :: function的向量

c – 具有不同签名的std :: function的向量

作者:互联网

我有许多具有不同签名的回调函数.理想情况下,我想将它们放在一个向量中,并根据某些条件调用适当的一个.

例如

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但没有设法实现我想要的.

这样的事情可能吗?

解决方法:

在将func2放入带有错误类型的向量之后,您还没有说过您希望能够用func2做什么.

如果您提前知道参数,则可以轻松使用std :: bind将其放入向量中:

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

现在函数[1](“foo”)将调用func2(“foo”,5,6),并且每次都将5和6传递给func2.

使用lambda而不是std :: bind是一回事

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

如果您还不知道参数,可以绑定对某些变量的引用:

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

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

并使用lambda函数而不是std :: bind

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

这很丑陋,因为只要引用它们的可调用对象(闭包或绑定表达式)存在,就需要保持int变量.

标签:std-function,c,c11,stdvector
来源: https://codeday.me/bug/20190927/1822331.html