简体   繁体   中英

How can a C++ namespace be extended from within another namespace?

Let's assume there are a number of variables defined in namespace library::symbols that are supposed to initialize on startup, like this:

namespace library {
    class Symbol; // details not relevant here

    namespace symbols {
        inline const Symbol S1 = Symbol("S1");
        inline const Symbol S2 = Symbol("S2");
    }
}

Now, I need to add more of those from other places, referencing back into the symbols namespace (pseudo code):

namespace app {
    namespace ::library::symbols {
        inline const Symbol S3 = Symbol("S3");
        inline const Symbol S4 = Symbol("S4");
    }
}

The rationale behind this is to have an extensible set of global constants that can be compared, parsed and printed at runtime (example names S1...S4 are arbitrary here).

The example doesn't compile. I tried a bunch of ideas, but can't seem to find any solution yet. What am I missing? Is there a way to reopen and extend the library::symbols namespace? Is there an alternative to achieve this, eg via template specialization?


EDIT: Reframed the question and second code snippet to be more precise. The issue I have is how to extend a namespace outside the current namespace. In the example, I would need to extend symbols while inside namespace app .

So the question is if there's a way to alias back into a higher-level namespace without this causing the declaration of a new one.

Is there a way to reopen and extend the library::symbols namespace? 

Yes, you said it. Just reopen the library::symbols namespace and put more data in it. For example:

namespace library
{
    class Symbol;

    namespace symbols
    {
        inline const Symbol S1 = Symbol("S1");
        inline const Symbol S2 = Symbol("S2");
    }
}

// Maybe in another file
namespace library
{
    class Symbol;

    namespace symbols
    {
        inline const Symbol S3 = Symbol("S1");
        inline const Symbol S4 = Symbol("S2");
    }
}

namespace app
{
    using namespace library;

    Symbol dummy()
    {
        // Here use a namespace variable
        return symbols::S3;
    }
}

You just have to remember to include the correct header if you reopen the namespace in another file.

Just do what you did in the declaration of first set of variables:

namespace library {
    namespace symbols {
        inline const Symbol S3 = Symbol("S3");
        inline const Symbol S4 = Symbol("S4");
    }
}

Edit:

In the example, I would need to extend symbols while inside namespace app.

This isn't possible. The solution is to not try to do that. Close the namespace app , then follow the example I gave above. You can re-open app afterwards if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM