以 C++11 方式重写 boost 风味代码(Boost.Bind、Boost.Function)
Rewrite boost flavored code in C++11 manner (Boost.Bind, Boost.Function)
我有一些遗留代码,我想用C++11风格重写。有一些boost::function
定义如下
// void One::first(int)
boost::function<void()> a1 = boost::bind(&One::first, this, this->a);
// void Two::second()
boost::function<void()> a2 = boost::bind(&Two::second, this);
// void Three::third(int, const std::string &)
boost::function<void()> a3 = boost::bind(&Three::third, this, 8, str);
这些变量被传递给不同位置的函数foo
:
foo(somearg, a1);
foo(anotherarg, a2);
foo(othearg, a3);
其中foo
定义如下
void foo(const Obj &obj, boost::function<void()> caller) {
...
caller();
...
}
以 C++11 样式重写此代码的最佳方法是什么?
首先,只需将boost
替换为 std
,并包含C++标头<functional>
而不是 Boost 标头。标准function
和bind
基于Boost版本,并且大部分与Boost版本兼容。
你可以让它更通用:
template <typename Function>
void foo(const Obj &obj, Function caller) {
//...
caller();
//...
}
并避免function
包装器的开销(以及注释指出的模糊语义限制):
auto a1 = std::bind(&One::first, this, this->a);
foo(somearg, a1);
您可能会发现 lambda 语法比调用 bind
更具可读性:
auto a1 = [this]{first(a);};
相关文章:
- boost::bind()类似的东西,但用于函数调用
- 泛化传递给 boost::bind 的参数
- boost::bind函数缓冲区的最大大小
- 自 1.55 以来,boost::bind / boost::function 中的奇怪行为变化
- 使用 boost::bind 进行订阅回调时出错
- 如何使用 boost::bind 附加参数?
- boost::bind 无法绑定到纯虚拟基类中定义的非静态函数模板成员类型
- 如何正确绑定成员函数与 boost::bind
- 将 boost::function 和 boost::bind 替换为模板
- Boost Asio - boost::bind 导致程序崩溃
- 我可以使用 boost::bind 来存储不相关的对象吗?
- 在spirit parser Action中,在上下文参数上编译boost :: bind(成员函数)上的错误
- 如何使用 boost::bind 将返回 int 的函数转换为返回布尔值的函数
- boost::bind with member functions(作为boost::asio异步写入处理程序)
- 创建一个 boost::线程 带有 boost::bind() 或不带
- 如何使用 boost::bind 将静态成员函数绑定到 boost::function
- 为什么这"boost::bind"不编译?
- 访问Boost Bind时,共享库中的C 符号查找错误
- 使用 Boost.Bind 打印矢量元素
- 编译 Boost.Bind时出错