在打包代码中使用命名空间的最佳/最干净的方法是什么?
例如,在像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 都想重用相同的接口(因此它们都没有“独占”这些接口)。此外,假设项目确实非常大,并且每个文件夹中的类都需要适当的命名空间。
您将如何在这样的项目中应用命名空间?假设我在 namespace 中声明所有类 reusable/ ::reusable
。我应该将 reusable_if 中的接口放入命名空间::reusable
还是放入::reusable_if
?或者可能没有,因为它被组件1和组件2使用?
component1 和 component2 中的命名空间呢?有什么要记住的吗?关键字using
呢?假设我决定添加这个::reusable_if
命名空间。我可以将using reusable_if
头文件放入组件 1 和组件 2 中,前提using ...
是放在命名空间::component1
和::component2
?
我愿意接受任何建议,也包括与上述示例不一定相关的建议。