r/cpp_questions • u/CommandShot1398 • 5d ago
OPEN How does std::bind differentiate between arguments and pointer to an object?
Hi everyone,
I have difficulties understanding something:
class HttpServer {
public:
HttpServer(std::string_view address, uint16_t port):ioc{1},endpoint{boost::asio::ip::make_address(address)},
acceptor{ioc,{endpoint,port}} {
};
~HttpServer()=default;
void handle_request() {
for (;;) {
tcp::socket socket{ioc};
// Block until we get a connection
acceptor.accept(socket);
std::cout<<"connection accepted"<<std::endl;
std::thread{std::bind(
&HttpServer::do_session,this,
std::move(socket))}.detach();
}
}
void do_session(tcp::socket& socket) {
//handle request
}
private:
const boost::asio::ip::address endpoint;
uint16_t port;
boost::asio::io_context ioc;
tcp::acceptor acceptor;
};
In this piece of code, how does std::bind understand that it should infer this as a pointer to the object which own the function pointer (I'm not even sure if I stated it correctly)?
according to chatgpt
std::bind( function, argument1, argument2, argument3 )
is a template that takes a pointer to the function that it should return the wrapper for, along with the arguments and their placeholders. What I don't understand is how it differentiates between the "this" pointer and an argument? How does it know it should take the non-static member function and dereference it based on the address (or reference) of the object that owns it, rather than just using "this" pointer as another argument?
12
u/Dan13l_N 5d ago
This is likely done by template specialization. If the first argument of
std::bindis a non-static member function, the second argument must be a pointer to object you'll call the function on.