Dav*_*ing 5 c++ namespaces using-directives
考虑这个库头:
#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);
}
}
Run Code Online (Sandbox Code Playgroud)
detail命名空间是否成功地将库的客户端(以及库的其余部分实现)与此示例中的using-directive隔离开来?我对于为什么"使用命名空间std"被认为是不良做法的讨论不感兴趣?即使某些论据甚至适用于"包含良好"的使用指令.
请注意,有两个关于相同情况但存在使用声明的问题:
这可以与它们中的任何一个组合,但编辑将是严重的.
您污染了自己的detail名称,但没有污染Lib或全局名称空间.所以假设一个负责任的成年人正在使用你的图书馆,他们就不会有无意的名字冲突:
#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
}
Run Code Online (Sandbox Code Playgroud)