【发布时间】:2014-04-25 20:59:18
【问题描述】:
在打包代码中使用命名空间的最佳/最干净的方法是什么?
例如在像 boost 这样的库中,似乎有非常有条理的命名空间管理,使用了一些允许消除名称歧义的技术。然而,重要的是,人们不会看到太多类似
的代码typedef namespace1::namespace2::sth_else::a_class<namespace3::namespace4::b_class> type;
通常,没有太多的跨命名空间,这表明良好的架构以及良好的命名空间管理。问题是:什么是好的命名空间管理?
假设我们有这样的文件结构:
component1/... (depends on reusable_if)
component2/... (depends directly on reusable_if and on component 1)
reusable/
reusable/some_part/
reusable/some_part/...
reusable/some_other_part/
reusable/some_other_part/...
reusable/SthThatUsesBothReusableParts.h (implements reusable_if/ISth.h)
reusable/SthThatUsesBothReusableParts.cpp (implements reusable_if/ISth.h)
reusable_if/
reusable_if/ISth.h (pure abstract class)
reusable_if/ISthElse.h (pure abstract class)
main.cpp (e.g. instantiates SthThatUsesBothReusableParts and passes to component1/2)
之所以有 reusable_if/ 文件夹是因为 component1 和 component2 都想重用相同的接口(因此它们都没有“独占”这些接口)。此外,假设该项目确实非常大,并且需要为每个文件夹中的类提供适当的命名空间。
您将如何在这样的项目中应用命名空间?
假设我在命名空间::reusable 中声明了所有可重用/ 类。我应该将 reusable_if 中的接口放入命名空间::reusable 还是::reusable_if?或者因为它被component1和component2使用,所以可能没有?
component1 和 component2 中的命名空间呢?有什么要记住的吗?
关键字using 怎么样?假设我决定添加这个 ::reusable_if 命名空间。如果using ... 放在命名空间::component1 和::component2 中,我可以将using reusable_if 放入component1 和component2 的头文件中吗?
我愿意接受任何建议,包括与上述示例不一定相关的建议。
【问题讨论】:
-
通常保持命名空间层次结构尽可能平坦。
-
@g-makulik 但不要比避免名称冲突所必需的更扁平
标签: c++ architecture namespaces inversion-of-control packaging