In my class I have the need to keep a pointer to a structure which is defined in a library I use to implement it. Since this library is only used within the implementation file I would like to avoid including it in the header directly. At the same time I want to avoid polluting the namespace. Thus I would like to do:
/* HEADER */
class Foo {
private:
struct ImplementationDetail;
ImplementationDetail * p;
};
/* SOURCE */
#include <Library.h>
using Foo::ImplementationDetail = Library::SomeStruct;
But this doesn't work, and I'm currently falling back on PIMPL:
/* HEADER */
class Foo {
private:
struct ImplementationDetail;
ImplementationDetail * p_;
};
/* SOURCE */
#include <Library.h>
struct ImplementationDetail {
Library::SomeStruct * realp_;
}
Is there a way to avoid the double dereference? Is the reason for my non-working first solution due to unknown pointer sizes?
This is an incorrect declaration:
usingdoesn't work this way. In C++11usingcannot create an alias for a name in one namespace to a name in another namespace. In C++03, allusingdoes is bring some other namespace in to global visibility in the current translation unit. It's not used to create aliases in C++03, as you seem to want to do here.pimpl is the de-facto method for doing what you're trying to do, but in your header file instead of trying to use a
ImplementationDetail*, I would use a simplevoid*. Using avoid*in this manner is guaranteed to be correct according to the Standard:Use
static_cast2 to go from avoid*to your actual type:You can avoid using the
void*in a conformant way by forward-declaring your library type:And then no ugly cast is needed in the implementation.
2 Use
static_cast: Orreinterpret_cast