The traditional PImpl Idiom is like this:
#include <memory>
struct Blah
{
//public interface declarations
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
//in source implementation file:
struct Blah::Impl
{
//private data
};
//public interface definitions
However, for fun, I tried to use composition with private inheritance instead:
[Test.h]
#include <type_traits>
#include <memory>
template<typename Derived>
struct PImplMagic
{
PImplMagic()
{
static_assert(std::is_base_of<PImplMagic, Derived>::value,
"Template parameter must be deriving class");
}
//protected: //has to be public, unfortunately
struct Impl;
};
struct Test : private PImplMagic<Test>,
private std::unique_ptr<PImplMagic<Test>::Impl>
{
Test();
~Test();
void f();
};
[first translation unit]
#include "Test.h"
int main()
{
Test t;
t.f();
}
[second translation unit]
#include <iostream>
#include <memory>
#include "Test.h"
template<>
struct PImplMagic<Test>::Impl
{
Impl()
{
std::cout << "It works!" << std::endl;
}
int x = 7;
};
Test::Test()
: std::unique_ptr<Impl>(new Impl)
{
}
Test::~Test() // required for `std::unique_ptr`'s dtor
{}
void Test::f()
{
std::cout << (*this)->x << std::endl;
}
I like the way this alternate version works, however I'm curious if it has any major drawbacks over the traditional version?
EDIT: DyP has kindly provided yet another version, which is even 'prettier'.