fork download
  1. #include <iostream>
  2.  
  3. // A factory class that will not call anything except constructor. Even if it could.
  4. template<typename T> class HonestFactory
  5. {
  6. // A factory class that would like to mess with private methods. But it can't.
  7. friend class HeinousFactory;
  8.  
  9. // This will ensure only Heinous one can use it.
  10. HonestFactory() { }
  11.  
  12. // Real one should be a variadic template.
  13. T Create()
  14. {
  15. return T{};
  16. }
  17. };
  18.  
  19. class Foo
  20. {
  21. friend class HonestFactory<Foo>; // We trust the honest one.
  22. Foo() { }
  23. int m_foo {0};
  24.  
  25. public:
  26. int m_bar {1};
  27. };
  28.  
  29. class HeinousFactory
  30. {
  31. public:
  32. Foo CreateFoo()
  33. {
  34. HonestFactory<Foo> factory;
  35. Foo foo = factory.Create();
  36. //foo.m_foo = 1; // Error.
  37. foo.m_bar = 1;
  38. return foo;
  39. }
  40. };
  41.  
  42. int main()
  43. {
  44. //Foo foo1; // No.
  45. //HonestFactory<Foo> factory; // Nope.
  46. HeinousFactory factory;
  47. Foo foo2 = factory.CreateFoo();
  48. std::cout << foo2.m_bar << std::endl;
  49. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
1