C++: #including <thread> redefines winsock function bind(...)?

bind, c++, multithreading, winsock

Solution

Short answer

Don't use `using namespace std;`.

Slightly longer answer

There's `std::bind` in C++11. `using namespace std;` will introduce this version of `bind` to the global namespace, which can lead to problems. You can use `::bind` for your original WinSock bind, but better stay safe and don't use a whole namespace.

Why does this happen if you include `<thread>`? Because `std::thread` might use `std::bind` internally, for which it includes `<functional>` where `std::bind` is declared.

Problem

Beginning of my CPP file: ``` #include "stdafx.h" #include <iostream> #include <string> #include <sstream> #define WIN32_MEAN_AND_LEAN #include <winsock2.h> #include <windows.h> ``` (straight out of madwizard.org winsock tutorial). Everything works fine but now whenever i just add `#include <thread>` (anywhere before/after other includes) the following doesnt compile: ``` if (bind(hSocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr)) != 0 ) { throw ROTException("could not bind socket."); } ``` The beginning of error is: ``` error C2678: binary '!=' : no operator found which takes a left-hand operand of type 'std::_Bind<_Forced,_Ret,_Fun,_V0_t,_V1_t,_V2_t,_V3_t,_V4_t,_V5_t,<unnamed-symbol>>' (or there is no acceptable conversion) 1> with 1> [ 1> _Forced=false, 1> _Ret=void, 1> _Fun=SOCKET &, 1> _V0_t=sockaddr *, 1> _V1_t=unsigned int, 1> _V2_t=std::_Nil, 1> _V3_t=std::_Nil, 1> _V4_t=std::_Nil, 1> _V5_t=std::_Nil, 1> <unnamed-symbol>=std::_Nil 1> ] 1> c:\home\vs\vc\include\exception(522): could be 'bool std::operator !=(const std::exception_ptr &,const std::exception_ptr &)' ``` So its like bind changed type from int to void. If i just write ``` bind(hSocket, reinterpret_cast<sockaddr*>(&sockAddr), sizeof(sockAddr)); ``` It will compile, but it will not work. What am i doing wrong ?

Original source