Is using-directive in the part namespace problematic?

Consider this library header:

#include<vector> #include<algorithm> #include<iostream> namespace Lib { namespace detail { using namespace std; template<class T> void sort_impl(istream &in,ostream &out) { vector<T> v; { int n; in >> n; v.resize(n); } for(auto &i : v) cin >> i; sort(v.begin(),v.end()); for(auto i : v) out << i << endl; } } inline void sort_std() { detail::sort_impl<int>(std::cin,std::cout); } } 

Does the client namespace (and the rest of the library implementation) successfully isolate the detail namespace from the using directive in this example? I'm not interested in discussing the question “ Why use the std namespace” is considered bad practice? even if some arguments apply even to “well-contained” usage directives.

Please note that there are two existing questions regarding the same situation, but using -declarations:

It can be combined with any of them, but editing will be serious.

+5
source share
2 answers

You are polluting your own detail namesapce, but not Lib or global namespaces. Therefore, assuming the responsible adult is using your library, they will not have unintended name conflicts:

 #include <vector> namespace Lib { namespace detail { using namespace std; } } using namespace Lib; int main() { vector<int> v; // This is an error, vector not declared in this scope } 
+6
source

No , the detail namespace will not isolate clients from the nested using directive. [namespace.udir] says in some detail that

A using-directive indicates that names in the nomenclature namespace can be used in the area in which using-directive appears after using-directive . During an unqualified name lookup, names appear as if they were declared in the closest spanning namespace containing using-directive and the nominated namespace. [Note: In this context, “contains” means “contains directly or indirectly”. - final note]

A small example

 #include <iostream> namespace foo { namespace detail { using namespace std; } } int main() { foo::detail::cout << "Hello World!\n"; // nothing is stopping me from doing that using namespace foo::detail; cout << "Hello World!\n"; } 

STL gives a good explanation of how name lookup works in its Core C ++ video , 1 of n .

+3
source

Source: https://habr.com/ru/post/1271707/


All Articles