fork download
  1. #include <iostream>
  2. #include <type_traits>
  3. #include <memory>
  4.  
  5. template<typename Derived>
  6. struct PImplMagic
  7. {
  8. PImplMagic()
  9. {
  10. static_assert(std::is_base_of<PImplMagic, Derived>::value,
  11. "Template parameter must be deriving class");
  12. }
  13. //protected: //has to be public, unfortunately
  14. struct Impl;
  15. };
  16.  
  17. struct Test : private PImplMagic<Test>, private std::unique_ptr<PImplMagic<Test>::Impl>
  18. {
  19. Test();
  20. void f();
  21. };
  22.  
  23. int main()
  24. {
  25. Test t;
  26. t.f();
  27. }
  28.  
  29. template<>
  30. struct PImplMagic<Test>::Impl
  31. {
  32. Impl()
  33. {
  34. std::cout << "It works!" << std::endl;
  35. }
  36. int x = 7;
  37. };
  38.  
  39. Test::Test()
  40. : std::unique_ptr<Impl>(new Impl)
  41. {
  42. }
  43.  
  44. void Test::f()
  45. {
  46. std::cout << (*this)->x << std::endl;
  47. }
  48.  
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
It works!
7