c++ - 为什么这里 `boost::bind()`不能换成 `std::bind()`呢?

标签 c++ boost c++11 bind boost-asio

<分区>

这部分代码来自example :

int main()
{
  boost::asio::io_service io;
  printer p(io);
  boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
  io.run();
  t.join();

  return 0;
}

如果我将 boost::bind(&boost::asio::io_service::run, &io) 替换为 std::bind(&boost::asio::io_service::run, &io) 我得到编译错误:

.../usr/lib/c++/v1/functional:1843:1: note: candidate template
  ignored: couldn't infer template argument '_Fp'
bind(_Fp&& __f, _BoundArgs&&... __bound_args)
^
/usr/lib/c++/v1/functional:1852:1: note: candidate template
  ignored: couldn't infer template argument '_Rp'
bind(_Fp&& __f, _BoundArgs&&... __bound_args)
^
1 error generated.

为什么会出现这个错误?

为什么 std::bind(&printer::print1, &p) 有效,但是 std::bind(&boost::asio::io_service::run, &io) 不起作用?

最佳答案

编译器告诉您它无法确定 std::bind 的第一个参数的类型。

如果您查看 io_service::run,您会发现它已过载。编译器有一个选择,这可能是编译器无法确定类型的原因。要对此进行测试,您可以使用强制转换:

std::bind(static_cast<size_t (boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io)

这种方式使选择在代码中明确。

使用现代编译器,您根本不需要使用绑定(bind)。你可以这样做:

[&]() { io.run(); }

这避免了 std::bind 模板的所有问题。您需要考虑变量的生命周期和拷贝与引用。

关于c++ - 为什么这里 `boost::bind()`不能换成 `std::bind()`呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20158311/

相关文章:

c++ - 我如何强制编译器生成的类的复制构造函数*不*被编译器内联?

c++ - 从 WinAPI 中的编辑窗口正确提取 int 以进行逻辑测试

c++ - 如何在 C++ 中设计高效的图像缓冲区?

Ubuntu boost b2 错误 : Cannot use --layout=system with --build-type complete

c++ - 仅运行一次函数的标准库函数

c++ - 使用 std::string 时为 "error: no match for ‘operator<<"

c++ - 高效的算法来获得圆心的圆心

C++ boost : is it included by default in most Linux distros?

c++ - 如何获得有关旧异常规范的警告

c++ - 使用聚合初始化和成员初始化器初始化结构