Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

C++ namespaces advice

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 */
        }
    }
}

As opposed to:

namespace tier1::tier2::tier3
{
}

à la 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

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

UPDATE

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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:

  • they have methods
  • they can control access
  • they cannot be re-opened

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...