using声明应该有多窄

How narrow should a using declaration be?

本文关键字:声明 using      更新时间:2023-10-16

我有一个使用std::string的小类widget。它在许多地方使用,通常与std::vector结合使用。所以你可以看到,typename变得很长很烦人。

我想使用using关键字,即using std::string;

问题是,把它放在哪里最好?

// widget.h file
#ifndef WIDGET
#define WIDGET
// (1)
namespace example {
    // (2)
    namespace nested {
        // (3)
        class widget {  
        public:
            // (4)
            ...
        private:
            // (5)
            std::string name_;
            ...
        };
    }
}
#endif

我的问题是:

  1. 如果我把它放在(1)中,那么包括widget.h的每个人的范围都会被string污染?
  2. (2)(3)的地方,情况与1相同。只有名称空间exampleexample::nested将在包含widget.h的第二个文件中被污染?
  3. 在地方(4)(5),声明是相当孤立的,但它会在实现(Cpp)文件和继承类可见?

提前感谢!

不要在(1)中这样做。
每个人都会诅咒你的名字一千年。作为类的用户,我不介意您污染自己的名称空间。但是,如果您污染了我的任何名称空间(包括global),我会感到不安,因为这会影响我的代码的编译方式。为什么使用命名空间std"被认为是不好的做法?

你不能在(4)或(5)处使用它。

因为我(个人)想把它绑定在尽可能靠近使用点的地方(以防止污染)。
你能做的最好的是(3)。

但我甚至不会那样做。我对任何标准的东西都很明确。但是我将定义我的容器类型。

private: //(so at 5) Don't need to expose internal details of your class.
    typedef std::vector<std::string>   MyCont;

这是一种更好的技术,因为您只需要在一个地方进行更改,并且更改将级联。

// Sub typedefs now will no longer need to change if you change
// The type of container. Just change the container typedef and
// now the iterators are automatically correct.
public: //(so at 4)  Iterators are public (and not exposing the implementation).
    typedef MyCont::iterator       iterator;
    typedef MyCont::const_iterator const_iterator;