using声明应该有多窄
How narrow should a using declaration be?
我有一个使用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)
中,那么包括widget.h
的每个人的范围都会被string
污染? - 在
(2)
和(3)
的地方,情况与1相同。只有名称空间example
和example::nested
将在包含widget.h
的第二个文件中被污染? - 在地方
(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;
相关文章:
- 在"template"和函数声明之间使用:template<typename trait> using tr = base_trait<trait> void fn(tr::t
- 是否可以使用 using 将基类中的公共成员重新声明为派生类中的私有成员?
- 如何正确转发声明结构"using XXX"?
- 我可以在using声明中正确使用C++20概念吗
- using声明不能引用类成员
- 是否可以在 using 声明中引用用户定义的转换模板?
- 如何使用模板声明"std::array" "using"
- 是否可以为成员的方法编写类似于固有方法的 using 声明?
- 指定面向具有相同名称的不同函数的类内 using 声明
- 引用 using 声明引入的功能的句子是什么意思?
- 为什么名称查找在找到使用 using 指令隐式声明的实体时不停止?
- 通过派生类模板参数指定基类模板参数之一。如何使用基类的 using 声明
- 在 C++ 中使用关键字 using 声明模板化函数指针的语法
- 何时使用using声明
- 为什么以及如何"using namespace"声明会混淆C++中的编译器?
- 为什么使用using声明引入的私有基类中的成员模板不可访问
- 'using'声明为SFINAE
- using声明如何减少可用于在没有 ADL 的情况下查找的名称
- 我可以在C++类中声明"using namespace"吗?
- 使用嵌套命名空间声明"using namespace"时出错 ( "namespace xxx::yyy not allowed in using-declaration" )