以 C++11 方式重写 boost 风味代码(Boost.Bind、Boost.Function)

Rewrite boost flavored code in C++11 manner (Boost.Bind, Boost.Function)

本文关键字:Boost Bind Function 代码 方式 C++11 重写 boost      更新时间:2023-10-16

我有一些遗留代码,我想用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 标头。标准functionbind基于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);};