fork download
  1. #include <cstdio> // for printf.
  2. #include <type_traits> // for is_reference, remove_reference.
  3. #include <typeinfo> // for typeid.
  4.  
  5. template<typename T>
  6. struct mutable_value
  7. {
  8. mutable_value(T val = 0) : val(val) { this->p_val = &this->val; }
  9. auto get_value() const -> T & { return *this->p_val; }
  10. private:
  11. T val;
  12. T *p_val;
  13. };
  14.  
  15. template<typename T>
  16. struct mutable_value_for_ref
  17. {
  18. typedef typename std::remove_reference<T>::type ref_dropped_t;
  19.  
  20. mutable_value_for_ref(T ref) : p_val{ &ref }
  21. {
  22. }
  23.  
  24. auto get_value() const -> ref_dropped_t &{ return *this->p_val; }
  25. private:
  26. ref_dropped_t *p_val;
  27. };
  28.  
  29. template<typename T>
  30. struct unko_meta
  31. {
  32. typedef
  33. typename std::conditional
  34. <
  35. std::is_reference<T>::value,
  36. mutable_value_for_ref<T>,
  37. mutable_value<T>
  38. >::type type;
  39. };
  40.  
  41. template<typename T>
  42. struct yakitori
  43. {
  44. yakitori(T t) : x(t) { }
  45.  
  46. auto get() const -> T & { return this->x.get_value(); }
  47.  
  48. typename unko_meta<T>::type x;
  49. };
  50.  
  51.  
  52. auto main() -> int
  53. {
  54. int i1 = 100;
  55. yakitori<int> const v1{ i1 };
  56. std::printf("--%s\n", typeid(v1.x).name());
  57. v1.get()++;
  58. std::printf("org:%d , yakitori:%d\n", i1, v1.get());
  59.  
  60. int i2 = 200;
  61. int const &r2 = i2;
  62. yakitori<int const> const v2{ r2 };
  63. std::printf("--%s\n", typeid(v2.x).name());
  64. i2++;
  65. std::printf("org:%d , yakitori:%d\n", i2, v2.get());
  66.  
  67. int i3 = 300;
  68. yakitori<int &> const v3{ i3 };
  69. std::printf("--%s\n", typeid(v3.x).name());
  70. v3.get()++;
  71. std::printf("org:%d , yakitori:%d\n", i3, v3.get());
  72.  
  73. int i4 = 400;
  74. int const &r4 = i4;
  75. yakitori<int const &> const v4{ r4 };
  76. std::printf("--%s\n", typeid(v4.x).name());
  77. i4++;
  78. std::printf("org:%d , yakitori:%d\n", i4, v4.get());
  79. }
  80.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
--13mutable_valueIiE
org:100 ,  yakitori:101
--13mutable_valueIKiE
org:201 ,  yakitori:200
--21mutable_value_for_refIRiE
org:301 ,  yakitori:301
--21mutable_value_for_refIRKiE
org:401 ,  yakitori:401