fork download
  1. struct constRef
  2. {
  3. int const& _t;
  4. constRef(int const& ro) : _t(ro) {}
  5. constRef(constRef const& rxo) : _t(rxo._t) {}
  6.  
  7. int const & t() const { return _t; }
  8. static constRef Make(int const & t) { return t; }
  9. };
  10.  
  11. struct Ref
  12. {
  13. int& _t;
  14. Ref(int& ro) : _t(ro) {}
  15. Ref(Ref const& rxo) : _t(rxo._t) {}
  16. operator constRef() const { return constRef(_t); }
  17.  
  18. int& t() { return _t; }
  19. static Ref Make(int& t) { return t; }
  20. };
  21.  
  22.  
  23. int main()
  24. {
  25. int foo = 5;
  26. Ref foo2(foo);
  27. constRef r(foo2); // non-const -> const This compiles.
  28. constRef c(r); // const -> const This compiles.
  29. Ref other = Ref::Make(foo); // non-const -> non-const This compiles
  30. Ref bar(r); // const -> non-const This fails to compile
  31.  
  32. return 0;
  33. }
  34.  
  35. int& MakeRef(int& t) { return t; }
  36.  
  37. int main2()
  38. {
  39. int foo = 5;
  40. const int& r(foo); // non-const -> const
  41. const int& c(r); // const -> const This compiles.
  42. int& other = MakeRef(foo); // non-const -> non-const This compiles.
  43. int& bar(r); // const -> non-const This fails to compile.
  44.  
  45. return 0;
  46. }
  47.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:30:14: error: no matching function for call to ‘Ref::Ref(constRef&)’
prog.cpp:30:14: note: candidates are:
prog.cpp:15:5: note: Ref::Ref(const Ref&)
prog.cpp:15:5: note:   no known conversion for argument 1 from ‘constRef’ to ‘const Ref&’
prog.cpp:14:5: note: Ref::Ref(int&)
prog.cpp:14:5: note:   no known conversion for argument 1 from ‘constRef’ to ‘int&’
prog.cpp: In function ‘int main2()’:
prog.cpp:43:15: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’
prog.cpp:41:16: warning: unused variable ‘c’ [-Wunused-variable]
prog.cpp:42:10: warning: unused variable ‘other’ [-Wunused-variable]
prog.cpp:43:10: warning: unused variable ‘bar’ [-Wunused-variable]
stdout
Standard output is empty