是否可以将绑定函数存储在容器中?
Can I store bound functions in a container?
请考虑以下代码:
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
相同。
相关文章:
- 添加存储在向量中的大整数的函数出现问题
- 存储在类中的函数指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 在函数内创建的对象的范围 - 如果在函数外部存储和访问引用,它们是否有效?
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- C++ SSE 内部函数:将结果存储在变量中
- 如何创建存储指向成员函数的指针的类 (C++)
- 存储函数指针的正确语法
- 如何捕获函数参数并存储函数指针以供以后在 C++11 中执行?
- 存储函数返回值或立即使用c++
- 自动变量可存储函数指针到std :: max
- 如何在 c++ 结构中的 void* 变量中调用存储函数(回调)
- 存储函数调用和以后调用的参数列表
- C++如何在内存中存储函数和对象
- 如何在类的成员中存储函数?(使用函数作为回调)
- C++:传递动态函数和存储函数
- 存储函数指针以供以后使用
- 不存储函数返回句柄时的内存管理
- 我想存储函数的void指针以及它们的类型
- Const Auto&用于存储函数结果,值得吗?