fork download
  1. #include <iostream>
  2. #include <type_traits>
  3.  
  4. template<typename Derived>
  5. class MyObject {
  6. public:
  7. MyObject() : theRealInstance(static_cast<Derived*>(this)) {
  8. // Check the available interface as soon an instance is created
  9. void (Derived::*op1)(void) = &Derived::methodImpl;
  10. (void)op1;
  11. }
  12.  
  13. void method() {
  14. theRealInstance->methodImpl();
  15. }
  16.  
  17. private:
  18. Derived* theRealInstance;
  19. };
  20.  
  21. struct MyImpl : public MyObject<MyImpl> {
  22. void methodImpl() { std::cout << "method implementation" << std::endl; }
  23. };
  24.  
  25. struct MyWrongImpl : public MyObject<MyWrongImpl> {
  26. };
  27.  
  28. void test_alias(){
  29. MyImpl m;
  30. m.method();
  31.  
  32. // Uncomment to see the compile time error
  33. // MyWrongImpl w;
  34. }
  35.  
  36. int main() {
  37. test_alias();
  38. return 0;
  39. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
method implementation