c++namespaces

Adding items to an aliased namespace


I'm using a namespace to switch between different versions of my database implementation. My client code should not need to know the details so I use a namespace alias to hide the specific version from the client code.

#db_v1.h

 namespace db_v1
 {
     class Database ...
 }

#db_def.h

 #ifdef _DB_V1
     #include "db_v1.h"
 #endif

 namespace db = db_v1;

Now if I want to extend the namespace with additional items, which are not version specific, I would like to add them to the namespace db, but the problem is that I can not use namespace db because it is an alias.

#db_global.h

namespace db   <-- should be using the namespace for the current version
{
    typedef enum
    {
         OK
    } value;
}

Obviously I get an error here because the namespace db already exists, while what I really want is, to extend the namespace without knowing which version is the current one.

As far as I can see, I would have to put such a definition into a separate namespace like db_global or I would have to duplicate such symbols in all versions, which I don't really like.

Is there some way to define it such that I can write in the client code something like:

 x = db::value::OK;

Solution

  • Maybe

    #ifdef _DB_V1
        #include "db_v1.h"
    #endif
    
    namespace db {
        using namespace db_v1;
    }
    

    in db_def.h instead of namespace db = db_v1;? This way all contents of db_v1 are imported into db namespace. Obviously, it may be conditionally-compiled:

    namespace db {
    #ifdef _DB_V1
        using namespace db_v1;
    #elif defined _DB_V2
        using namespace db_v2;
    #endif
    }
    

    For example, this code works well:

    namespace db_v1 {
        void foo(){}
    }
    
    namespace db_v2 {
        void foo(){}
    }
    
    namespace db {
        using namespace db_v1;
    }
    
    namespace db {
        typedef enum
        {
             OK
        } value;
    }