user1834749
user1834749

Reputation: 23

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

I'm trying to use boost::bind with boost::function,but a compile error appeared. why can't bind a placeholder to the function object?

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;
}

Upvotes: 2

Views: 718

Answers (3)

user1838244
user1838244

Reputation: 16

Note: by looking at http://my.oschina.net/yellia/blog/90678, the author explains the implementation of boost::bind clearly and simply. I hope it would help you.哈哈

Upvotes: 0

mark
mark

Reputation: 7677

If you cant change the signature you need to pass the value for the error_code to bind instead of a placeholder, so that it can supplied when the function is called

i.e.:

#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;
}

Upvotes: 2

Ralf
Ralf

Reputation: 9573

Your signatures don't match. Try this:

#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;
}

Compilation tested under gcc with g++ main.cpp -lboost_system -lpthread

For future reference, it helps to add

  • fully compilable examples
  • the complete compilation/linker error message

when posting snippets like the above to save people that want to help you time.

Upvotes: 2

Related Questions