详细名称空间中的using指令是否有问题? [英] Is a using-directive in a detail namespace problematic?

查看:94
本文介绍了详细名称空间中的using指令是否有问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此库头:

#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);
  }
}

在此示例中,detail名称空间是否成功地将库的客户端(以及库的其余实现)与 using-directive 隔离开?我对为什么使用命名空间标准"的讨论不感兴趣;被认为是不好的做法?,即使某些论点甚至适用于包含良好的" using-directives .

Does the detail namespace successfully isolate the clients of the library (and the rest of library's implementation) from the using-directive in this example? I'm not interested in the discussion at Why is "using namespace std" considered bad practice?, even though some of the arguments apply even to "well contained" using-directives.

请注意,存在两个有关相同情况的现有问题,但存在 using-declarations :

Note that there are two existing questions concerning the same situation but with using-declarations:

  • Using declarations in private namespaces in header files
  • Elegant way to prevent namespace poisoning in C++ (whose one answer is really an answer to the "bad practice" question above)

这可以与它们中的任何一个结合使用,但是编辑会很严格.

This could be combined with either of them, but the editing would be severe.

推荐答案

您污染自己的detail名称空间,而不污染Lib或全局名称空间.因此,假设有责任心的成年人正在使用您的图书馆,那么他们不会发生无意的名字冲突:

You pollute your own detail namesapce, but not the Lib or global namespaces. So assuming a responsible adult is using your library, they won't have unintentional name collisions:

#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
}

这篇关于详细名称空间中的using指令是否有问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆