fork download
  1. #include <iostream>
  2. #include <type_traits>
  3. #include <typeinfo>
  4.  
  5. template<typename Derived>
  6. struct base
  7. {
  8. void const_method() const
  9. {
  10. static_cast<Derived*>(this)->method();
  11. }
  12.  
  13. void fixed_const_method() const
  14. {
  15. // base<derived> const*
  16. std::cout << typeid(this).name() << std::endl;
  17. // base<derived>
  18. std::cout << typeid(typename std::remove_pointer<decltype(this)>::type).name() << std::endl;
  19. // base<derived>
  20. std::cout << typeid(decltype(*this)).name() << std::endl;
  21. // derived const*
  22. std::cout << typeid(typename std::conditional<
  23. std::is_const<
  24. typename std::remove_pointer<decltype(this)>::type>::value,
  25. Derived const* const,
  26. Derived* const>::type).name() << std::endl;
  27.  
  28. static_cast<
  29. typename std::conditional<
  30. std::is_const<
  31. typename std::remove_pointer<decltype(this)>::type>::value,
  32. Derived const* const,
  33. Derived* const>::type>(this)->method();
  34. }
  35. };
  36.  
  37. struct derived : public base<derived>
  38. {
  39. void method() const
  40. {
  41. std::cout << "const method" << std::endl;
  42. }
  43.  
  44. void method()
  45. {
  46. std::cout << "non-const method" << std::endl;
  47. }
  48. };
  49.  
  50. int main()
  51. {
  52. derived d;
  53. d.fixed_const_method();
  54.  
  55. return 0;
  56. }
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
PK4baseI7derivedE
4baseI7derivedE
4baseI7derivedE
PK7derived
const method