2

I'm trying to use two very large C++ libraries to write my own library and application set and there are using directives present in the main header classes of both libraries. The conflict lies in a single class, called vector (with the std::vector). One header has "using namespace std", and this messes things up.

Is there a way to exclude the identifier from the namespace, after the "using namespace" has already been written?

tmaric
  • 5,347
  • 4
  • 42
  • 75

4 Answers4

2

Is there a way to get the worms back into the can?

No.

The best option is to fix the header with the using directive. Remove it and add the required std:: prefixes to the declarations.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
2

There's no way to un-using in C++. In this case the only options I can think of are:

  • Have the library writers fix their library. using in a header is absolutely a bug in the library that should be fixed.

  • Completely isolate the two libraries from each other within your application by using separate, completely compartmentalized implementation files. If the two libraries would need to communicate you'd have to create some sort of mediator in your code to glue them together.

Mark B
  • 95,107
  • 10
  • 109
  • 188
1

You can create your own wrapper headers which include the library header while wrapping it in a namespace.

e.g., for any given header <brokenlib.h>, create "mybrokenlib.h" which looks like:

#ifndef MY_WRAPPER_HEADER_H
#define MY_WRAPPER_HEADER_H 1

namespace brokenlib
{
#include <brokenlib.h>
}

#endif

The header will obviously still have the using statement, but now it will inject the symbols from std into the brokenlib namespace instead of the global namespace.

Hopefully the library doesn't have many entry points that need wrapping.

EDIT: As pointed out by David Rodríguez, this only works if the libraries you're using are header-only. The only true solution is to get the libraries fixed (hope they're open-source?)

aalpern
  • 652
  • 4
  • 8
  • 2
    -1 (well, not really, but I really should) This will only work for header only libraries. If the library comes with a header and a binary, this will declare the symbols in the wrong namespace and will fail to link. – David Rodríguez - dribeas Feb 14 '12 at 16:54
  • Good point. I've gotten very used to header-only libraries (and more dynamic environments that support easy aliasing without problems like this). Edited my answer to include your point. – aalpern Feb 14 '12 at 16:59
0

I guess this simple shield would be a solution:

namespace myShield {
    #include "problematicheader.h"
}

EDIT: Only for header-only libraries :/

José Manuel
  • 1,056
  • 1
  • 9
  • 15
  • 3
    -1 (well, not really, but I really should) This will only work for header only libraries. If the library comes with a header and a binary, this will declare the symbols in the wrong namespace and will fail to link. – David Rodríguez - dribeas Feb 14 '12 at 16:54