0

I am working with some legacy code for a school project and am trying to capture if std::bind fails. This is the code currently in the project (not written by me) that is producing "C++ no operator matches these operands" error in VS 2019. I've tried comparing against a bool which is what it says std::bind returns to no avail.

if ( bind( socket, (const sockaddr*) &address, sizeof(sockaddr_in) ) < 0 )
{
    printf( "failed to bind socket\n" );
    Close();
    return false;
}

How else can I properly capture if std::bind fails within an if statement?

  • 7
    Do you have a `using namespace std;` before this code? It's likely trying to call `std::bind` which is for binding arguments to a function, version the socket.h `bind` which is what you want. Try changing `bind(...` to `::bind(` – gct Jan 22 '20 at 18:22
  • 3
    Sounds like you are using the wrong function. standard C++ introduced `std::bind` but it isn't for sockets. – NathanOliver Jan 22 '20 at 18:23
  • 2
    std::bind (https://en.cppreference.com/w/cpp/utility/functional/bind) is not bind (http://man7.org/linux/man-pages/man2/bind.2.html) – florgeng Jan 22 '20 at 18:25
  • Are you perhaps writing `using namespace std`? That is considered bad practice. I guess the bind isn't under a specific namespace: https://learn.microsoft.com/en-us/windows/win32/winsock/complete-server-code, so if you are assuming namespace std, then the bind is automatically assumed to be std::bind rather than bind. – Warpstar22 Jan 22 '20 at 18:34

1 Answers1

5

The C++ std::bind() function does not return a value on failure, it throws an exception instead.

But the code you have shown is NOT trying to use std::bind() at all, it is actually trying to use the WinSock bind() function instead, but it can't because std::bind() is in scope due to a previous using namespace std; or using std::bind; statement (most likely the former), and so the compiler is trying to call std::bind() instead.

You need to either get rid of the using statement, or else prefix the bind() call with the :: global scope resolution operator:

if ( ::bind( socket, (const sockaddr*) &address, sizeof(sockaddr_in) ) < 0 )
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770