samedi 23 mai 2015

cpp header-only library avoid "using namespace" pollution

I have a header-only cpp library with sevaral namespaces.

For example one header file may contain

//header1.h
namespace library{
namespace componentA{
   template<typename T>
   Someclass{};
}
}

And another one

//header2.h
namespace library{
namespace componentB{
   template<typename T>
   SomeOtherClass{
       void Foo(const componentA::Someclass<T>& reference);
       void Bar(const componentA::Someclass<T>& reference);
   };
}
}

Now while this works, having a header-only library it becomes tedious to write the namespace again and again, especially when you are having multiple classes and nested namespaces involved.

So i did this:

//new header2.h
namespace library{
namespace componentB{

   using namespace componentA;

   template<typename T>
   SomeOtherClass{
       void Foo(const Someclass<T>& reference);
       void Bar(const Someclass<T>& reference);
       void FooBar(const Someclass<T>& reference);
       void FooWithBar(const Someclass<T>& reference);
   };
}
}

While this is certainly more convenient to type, it has the problem that now a client of the library can also use Someclass by using the componentB namespace like this, which leads to an ambigous interface and ultimately to inconsistent code. For example a client now could use componentB::Someclass<T> even though it is originally defined in componentA

Is there a way to get the shorthand only available "privately"?

Aucun commentaire:

Enregistrer un commentaire