Is there a better way to express nested namespaces in C++ within the header

前端 未结 11 2458
天涯浪人
天涯浪人 2020-12-13 03:31

I switched from C++ to Java and C# and think the usage of namespaces/packages is much better there (well structured). Then I came back to C++ and tried to use namespaces the

11条回答
  •  再見小時候
    2020-12-13 03:44

    C++ namespaces are used to group interfaces, not to divide components or express political division.

    The standard goes out of its way to forbid Java-like use of namespaces. For example, namespace aliases provide a way to easily use deeply-nested or long namespace names.

    namespace a {
    namespace b {
    namespace c {}
    }
    }
    
    namespace nsc = a::b::c;
    

    But namespace nsc {} would then be an error, because a namespace may only be defined using its original-namespace-name. Essentially the standard makes things easy for the user of such a library but hard for the implementer. This discourages people from writing such things but mitigates the effects if they do.

    You should have one namespace per interface defined by a set of related classes and functions. Internal or optional sub-interfaces might go into nested namespaces. But more than two levels deep should be a very serious red flag.

    Consider using underscore characters and identifier prefixes where the :: operator isn't needed.

提交回复
热议问题