Javier
Javier

Reputation: 2848

How to solve two conflicting namespaces with the same name

I have in my own code an namespace core that is conflicting with the namespace core of a dynamic library that I am using. The problem appears because I can not modify neither one nor the other. The first core because is part of our team project, and the second because is part of the library. Is there a way to solve this situation?

Upvotes: 5

Views: 10804

Answers (3)

Aesthete
Aesthete

Reputation: 18858

Try turning your core namespace into a sub namespace.

This way you can get access to each 'core' namespace. This also explicitly shows which 'core' is being referred to. Even if the external library has the same function names you will be safe.

However, you mentioned that you can't actually change anything in the original code, so your only option is to use a different library and hope it doesn't have a 'core' namespace in it. Seems to me like it might be alot easier to convince your team to change their code.

// Your 'core' namespace, inside your own namespace.
namespace Mygame
{
  namespace core
  {
    void Foo();
  }
}

// Access both namespaces safely.
Mygame::core::Foo();
core::Foo();

Upvotes: 8

Potatoswatter
Potatoswatter

Reputation: 137960

Change

namespace core {
    // define namespace members
}

to

namespace myproject_core {} // namespace "declaration"
using namespace core = myproject_core; // "namespace alias"

// core:: refers only to your code now

namespace myproject_core {
    // define namespace members
}

Now the linker will see no conflict, and your code won't see the name change.


The problem appears because I can not modify neither one nor the other.

Well, if you can't modify anything then there is no solution. I've made an assumption in this answer, but maybe you can clarify what sort of change would be acceptable?

Upvotes: 1

WendiKidd
WendiKidd

Reputation: 4373

You're going to need to change the name of the namespace you have access to. Situations like this are why it's a good idea to give things you create (classes, libraries, namespaces...) a prefix that sets them apart from other items which might use similar names.

For example, if I have a game manager, I won't just call the class Manager. I'll call it MygameGameManager or something similar, to distinguish it from other classes--ie. if someone comes along later and adds a SoundManager to the project. It's important to find a balance in naming conventions between making things clear and distinct, and being too verbose in naming. The balance is out there, you just have to find it!

Upvotes: 1

Related Questions