是否可以将绑定函数存储在容器中?

Can I store bound functions in a container?

本文关键字:存储 函数 绑定 是否      更新时间:2023-10-16

请考虑以下代码:

void func_0()
{
std::cout << "Zero parameter function" << std::endl;
}
void func_1(int i)
{
std::cout << "One parameter function [" << i << "]" << std::endl;
}
void func_2(int i, std::string s)
{
std::cout << "One parameter function [" << i << ", " << s << "]" << std::endl;
}
int main()
{
auto f0 = boost::bind(func_0);
auto f1 = boost::bind(func_1,10);
auto f2 = boost::bind(func_2,20,"test");
f0();
f1();
f2();
}

上面的代码按预期工作。有什么方法可以将 f0、f1、f2 存储在容器中并像这样执行它:

Container cont; // stores all the bound functions.
for(auto func : cont)
{
func();
}

这个例子适合你吗?

std::vector<std::function<void()>> container{f0, f1, f2};
for (auto& func : container)
{
func();
}

你可以在这里阅读关于std::function的信息:

std::function 的实例可以存储、复制和调用任何 Callable 目标。。。

所以这个类模板的模板参数(在我们的例子中void()(只是Callable的签名。bind()所有调用中返回的内容正是表单void()可调用对象。

std::bind

不能保证为具有相同最终接口的函数返回相同的类型(final = 绑定后(。因此,不可以,您将无法在容器中存储与std::bind绑定的函数。您将不得不使用某种类型擦除技术将它们全部转换为同一类型,例如std::function.std::function<void()>容器将能够存储绑定函数(以与类型擦除相关的开销为代价(。

我不知道它是否适用于boost::bind,但我怀疑它在这方面与std::bind相同。