fork download
  1. #include <string>
  2. #include <iostream>
  3.  
  4. template <class T, class Factory> class add_ctor {
  5. public:
  6. add_ctor() : obj(Factory()) {
  7. }
  8. T* operator->() {
  9. return obj;
  10. }
  11. private:
  12. T* obj;
  13. };
  14.  
  15. class A {
  16. public:
  17. std::string v;
  18. static A createOne();
  19. private:
  20. A();
  21. };
  22. A A::createOne() {
  23. A a;
  24. a.v = "Hello!";
  25. return a;
  26. }
  27.  
  28. int main() {
  29. // this should work:
  30. add_ctor<A, decltype(&A::createOne)> added_a;
  31. std::cout << added_a->v << "\n";
  32.  
  33. // this should error:
  34. //A non_added_a;
  35. //std::cout << non_added_a.v << "\n";
  36. return 0;
  37. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In constructor 'add_ctor<T, Factory>::add_ctor() [with T = A, Factory = A (*)()]':
prog.cpp:30:42:   instantiated from here
prog.cpp:6:35: error: cannot convert 'A (*)()' to 'A*' in initialization
stdout
Standard output is empty