Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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?)

I guess this simple shield would be a solution:

namespace myShield {
    #include "problematicheader.h"
}

EDIT: Only for header-only libraries :/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top