Alternative PImpl Idiom - advantages vs disadvantages?
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:
#include <iostream>
#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();
void f();
};
int main()
{
Test t;
t.f();
}
template<>
struct PImplMagic<Test>::Impl
{
Impl()
{
std::cout << "It works!" << std::endl;
}
int x = 7;
};
Test::Test()
: std::unique_ptr<Impl>(new Impl)
{
}
void Test::f()
{
std::cout << (*this)->x << std::endl;
}
http://ideone.com/WcxJu2
I like the way this alternate version works, however I'm curious if it has
any major drawbacks over the traditional version?
No comments:
Post a Comment