Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two "using" collide?

Tags:

c++

So I have to use some members of Boost library and some from the std namespace. Right now, I have using boost::asio::ip::tcp; declared and am calling appropriate members with std:: and for example tcp::iostream server(). Is there any reason why I shouldn't add another using, namely using namespace std; and then call all the std things without std:: prefix? Can these two somehow collide or cause malfunction?

like image 309
Straightfw Avatar asked Jun 30 '26 16:06

Straightfw


1 Answers

Provided that it is usually considered a bad practice to have using directives that import names from the std namespace (especially when at namespace scope and/or in a header file), because it easily leads to name clashes, consider the following program:

namespace A { void foo() { } }
namespace B { void foo() { } }

int main()
{
    using namespace A;
    using namespace B;
    foo();
}

How should the compiler resolve the call to foo()? Well, it won't. It is ambiguous, because both A::foo() and B:foo() can now be referred to as the unqualified foo().

If there are entities with the same name in the std namespace and in the global namespace (or in any other namespace for which you have a using directive), ambiguities due to name clashes are likely to arise.

In your specific case, a using directive such as:

using namespace std;

Will be unlikely to clash with the name tcp introduced by your using declaration (notice, that a using declaration imports just one specific name and is, therefore, preferable).

Yet, it is still considered to be poor programming style and you should not do it, regardless of whether you have some other using directive or using declaration already in place.

like image 115
Andy Prowl Avatar answered Jul 02 '26 05:07

Andy Prowl