Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling code that uses socket function bind() with libcxx fails

Tags:

c++

c++11

bind

I am using the new libcxx library and I have a code that calls the socket function bind(). The problem is that when I type using namespace std; the compiler gives me an error for the following code:

int res = bind(sockfd, (struct sockaddr *)&myAddr, sizeof(myAddr));

The error using clang (svn build):

error: no viable conversion from '__bind<int &, sockaddr *, unsigned long>' to 'int'
 int res = bind(sockfd, (struct sockaddr *)&myAddr, sizeof(myAddr));

I think that the problem is that using namespace std; brings the function std::bind() from the header <functional> to the scope (although the header is not included). As I am using a third party library that uses the entire namespace std I can't easily change the class names to fully qualified names.

I was wondering whether this is a problem in the implementation of the library or whether there are some new rules in C++11 that might potentially break an old code that uses bind(). Any thoughts on this would be appreciated.

Thanks

Roman

like image 329
Roman Kutlak Avatar asked Apr 05 '12 20:04

Roman Kutlak


1 Answers

This isn't a problem in the implementation of the libraries. C++11 introduced its own std::bind function into namespace std, which is used to bind parameters to functions and support a bit of higher-order programming.

The reason for having namespace std is to help prevent new library functions and classes from causing breaking changes in existing code. The reason for this is that everything has a name starting with std::, which prevents name collisions.

However, if you write using namespace std; in your program, you're exposing yourself to potential breaking changes like this one, since the free function bind and the function std::bind can't necessarily be disambiguated.

To fix this, you can call bind as ::bind to make clear that it's in the global namespace, or you can remove the using namespace std; at the top of the program.

Hope this helps!

like image 85
templatetypedef Avatar answered Oct 21 '22 12:10

templatetypedef