使用声明应该有多窄?

Xla*_*ius 7 c++ namespaces using

我有这个小班widget使用了std::string.它在许多地方使用它,通常与a结合使用std::vector.所以你可以看到,类型名称变得非常冗长和烦人.

我想利用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
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 如果我把它放在那里,(1)那么所有包含的人widget.h都会被污染的范围string
  2. 在一些地方(2)(3),这是同样的故事在1只,该命名空间example,并example::nested会在包括第二个文件被污染widget.h
  3. 在地方(4)(5),声明是相当孤立的,但它会在实现(Cpp)文件和继承类中可见吗?

提前致谢!

Mar*_*ork 13

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

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

因为我(个人)希望尽可能地将其绑定到使用点(以防止污染).
你能做的最好的是(3).

但我甚至不会这样做.我对标准的任何内容都很明确.但我会输入我的容器类型.

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

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

// 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;
Run Code Online (Sandbox Code Playgroud)

  • 请注意,C++ 11别名语法也可用`使用MyCont = std :: vector <std :: string>;` (3认同)