C++ 命名空间建议

2022-01-14 00:00:00 namespaces c++

我只是在自学 C++ 命名空间(来自 C# 背景),我真的开始认为,即使 C++ 比大多数其他语言做得更好,嵌套命名空间也不是其中之一!

I'm just teaching myself C++ namespaces (coming from a C# background) and I'm really starting to think that even with all the things that C++ does better than most other languages, nested namespaces isn't one of them!

我是否正确地认为为了声明一些嵌套的命名空间,我必须执行以下操作:

Am I right in thinking that in order to declare some nested namespaces I have to do the following:

namespace tier1
{
    namespace tier2
    {
        namespace tier3
        {
            /* then start your normal code nesting */
        }
    }
}

相对于:

namespace tier1::tier2::tier3
{
}

在 C# 中?

当我需要转发声明时,这变得更加疯狂:

This becomes even more demented when I need to forward declare:

namespace tier1
{
    namespace tier2
    {
        namespace forward_declared_namespace
        {
            myType myVar; // forward declare
        }
        namespace tier3
        {
            /* then start your normal code nesting */
            class myClass
            {
                forward_declared_namespace::myType myMember;
            }
        }
    }
}

请记住,我开发的典型系统包括:

Bearing in mind that a typical system that I develop consists of:

MyCompany::MySolution::MyProject::System::[PossibleSections]::Type

这就是为什么您在 C++ 示例中很少看到命名空间的原因吗?还是通常只有单个(非嵌套)命名空间?

Is this why you don't tend to see much use of namespaces in C++ examples? Or usually only single (not nested) namespaces?

更新

对于任何感兴趣的人,这就是我最终解决这个问题的方式问题.

For anyone interested, this is how I ended up tackling this issue.

推荐答案

C++ 命名空间并不是一种设计机制――它们只是为了防止名称冲突.在 99.99% 的情况下,您确实不想或不需要使用嵌套命名空间.

C++ namespaces were not intended to be a design mechanism - they are there simply to prevent name clashes. You really don't want or need to use nested namespaces in 99.99% of situations.

在 C++ 中正确使用命名空间的一个很好的例子是 C++ 标准库.这个相当大的库中的所有内容都放置在一个名为 std 的命名空间中 - 没有尝试或不需要将库分解为(例如)一个 I/O 子命名空间、一个数学子命名空间命名空间、容器子命名空间等.

A good example of the correct use of namespaces in C++ is the C++ Standard Library. Everything in this quite large library is placed in a single namespace called std - there is no attempt or need to break the library up into (for example) an I/O sub-namespace, a math sub-namespace, a container sub-namespace etc.

在 C++ 中建模的基本工具是类(在某种程度上是模板),而不是命名空间.如果你觉得需要嵌套,你应该考虑使用嵌套类,它比命名空间有以下优点:

The basic tool for modelling in C++ is the class (and to some extent the template), not the namespace. If you feel the need for nesting, you should consider using nested classes, which have the following advantages over namespaces:

  • 他们有方法
  • 他们可以控制访问权限
  • 它们无法重新打开

考虑到这些,如果您仍然希望使用嵌套命名空间,请务必这样做 - 以这种方式使用它们在技术上没有任何问题.

Having considered these, if you still wish to use nested namespaces by all means do so - there is nothing technically wrong with using them in this way.

相关文章