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