fork(3) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4.  
  5. template <typename T>
  6. struct NonConst {typedef T type;};
  7. template <typename T>
  8. struct NonConst<T const> {typedef T type;}; //by value
  9. template <typename T>
  10. struct NonConst<T const&> {typedef T& type;}; //by reference
  11. template <typename T>
  12. struct NonConst<T const*> {typedef T* type;}; //by pointer
  13. template <typename T>
  14. struct NonConst<T const&&> {typedef T&& type;}; //by rvalue-reference
  15.  
  16. template<typename TConstReturn, class TObj, typename... TArgs>
  17. typename NonConst<TConstReturn>::type likeConstVersion(
  18. TObj const* obj,
  19. TConstReturn (TObj::* memFun)(TArgs...) const,
  20. TArgs... args) {
  21. return const_cast<typename NonConst<TConstReturn>::type>(
  22. (obj->*memFun)(args...));
  23. }
  24.  
  25. struct T {
  26. int arr[100];
  27. int const& getElement(size_t i) const{
  28. return arr[i];
  29. }
  30. int& getElement(size_t i) {
  31. return likeConstVersion(this, &T::getElement, i);
  32. }
  33. /*
  34.   int const& getElement() const{
  35.   return 42;
  36.   }
  37.   int& getElement() {
  38.   return likeConstVersion(this, &T::getElement);
  39.   }*/
  40. };
  41.  
  42. int main() {
  43. T t;
  44. int b=t.getElement(4);
  45. return 0;
  46. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
Standard output is empty