为什么这"boost::bind"不编译?

why doesn't this "boost::bind" compile?

本文关键字:编译 bind boost 为什么      更新时间:2023-10-16

我正在尝试使用boost::bind和boost::函数,但出现了编译错误。为什么不能将占位符绑定到函数对象?

void fun_1(const boost::system::error_code& error)
{
std::cout<<"test_1------------"<<std::endl;
}
void fun_2(int i)
{
std::cout<<"tset_2------------"<<std::endl;
}
int main(void)
{
boost::function0<void> fobj;
//fobj = boost::bind(&fun_1,boost::asio::placeholders::error);//compile failed
fobj = boost::bind(&fun_2,5);//syntax is ok
return 0;
}

您的签名不匹配。试试这个:

#include <boost/function.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
void fun_1(const boost::system::error_code& error)
{
std::cout<<"test_1------------"<<std::endl;
}
void fun_2(int i)
{
std::cout<<"tset_2------------"<<std::endl;
}
int main(void)
{
boost::function<void (const boost::system::error_code&)> fobj;
fobj = boost::bind(&fun_1,boost::asio::placeholders::error);
return 0;
}

g++ main.cpp -lboost_system -lpthread在gcc下进行编译测试

为了将来参考,添加有助于

  • 完全可编译的示例
  • 完整的编译/链接器错误消息

当发布如上所述的片段以节省想要帮助您的人的时间时。

如果无法更改签名,则需要传递要绑定的error_code的值,而不是占位符,以便在调用函数时提供该值

即:

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>
void fun_1(const boost::system::error_code& error)
{
std::cout<<"test_1------------"<<std::endl;
}
void fun_2(int i)
{
std::cout<<"tset_2------------"<<std::endl;
}
int main()
{
boost::function0<void> fobj;
//fobj = boost::bind(&fun_1,boost::asio::placeholders::error);//compile failed
fobj = boost::bind( &fun_1,
boost::system::errc::make_error_code( boost::system::errc::success ) );//compiles ok
// fobj = boost::bind(&fun_2,5);//syntax is ok
return 0;
}

注意:通过查看http://my.oschina.net/yellia/blog/90678,作者简单明了地解释了boost::bind的实现。我希望它能帮助你。哈哈