C++ Primer 4/e在Namespaces这个地方有一个警告:‘using directives, which inject all the names from a namespace, are deceptively simple to use: With only a single statement, all the member names of a namespace are suddenly visible. Although this approach may seem simple, it can introduce its own problems. If an application uses many libraries, and if the names within these libraries are made visible with using directives, then we are back to square one, and the global namespace pollution problem reappears.
Moreover, it is possible that a working program will fail to compile when a new version of the library is introduced. This problem can arise if a new version introduces a name that conflicts with a name that the application is using.
Another problem is that ambiguity errors caused by using directives are detected only at the point of use. This late detection means that conflicts can arise long after introducing a particular library. If the program begins using a new part of the library, previously undetected collisions may arise.
Rather than relying on a using directive, it is better to use a using declaration for each namespace name used in the program. Doing so reduces the number of names injected into the namespace. Ambiguity errors caused by using declarations are detected at the point of declaration, not use, and so are easier to find and fix.’
中文版的这样写:‘using指令会将某个namespace内的所有名称注射进来。无可否认这样用很方便:只需一条述句,namespace内的所有成员名称突然全部曝光。尽管这看起来很简单,却会引入一些问题。如果一个程式用了很多程式库,并以using指令来曝光这些程式库内的名称,那么我们又回到了原点:global命名空间的污染问题再次出现。
此外,导入一个新版程式库有可能使得原本正确的程式编译失败。是的,如果新版程式库导入一个程式已在使用的名称,问题就会发生。
另一个问题是,由using指令产生的歧义错误只能在使用时才被侦测到。这种后期侦测意味有可能在导入某个程式库后很长时间才出现冲突。如果程式开始使用这个新版程式库的某一新成分,上面所说的“未侦测到的冲突”就可能终于爆发。
与其倚赖using指令,不如对程式中用到的每个名称都使用using宣告式。这能够减少[注射进入当前namespace”的名称数。using宣告是导致的歧义错误会在宣告点而不是使用点上被侦测到,所以更加容易找到并修补。’
这个滥用using的困扰,却是心中的痛。