doc_template_assign.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2014-2014.
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. // See http://www.boost.org/libs/move for documentation.
  9. //
  10. //////////////////////////////////////////////////////////////////////////////
  11. #include <boost/move/detail/config_begin.hpp>
  12. #include <boost/move/detail/meta_utils_core.hpp>
  13. #include <boost/move/move.hpp>
  14. //[template_assign_example_foo_bar
  15. class Foo
  16. {
  17. BOOST_COPYABLE_AND_MOVABLE(Foo)
  18. public:
  19. int i;
  20. explicit Foo(int val) : i(val) {}
  21. Foo(BOOST_RV_REF(Foo) obj) : i(obj.i) {}
  22. Foo& operator=(BOOST_RV_REF(Foo) rhs)
  23. { i = rhs.i; rhs.i = 0; return *this; }
  24. Foo& operator=(BOOST_COPY_ASSIGN_REF(Foo) rhs)
  25. { i = rhs.i; return *this; } //(1)
  26. template<class U> //(*) TEMPLATED ASSIGNMENT, potential problem
  27. //<-
  28. #if 1
  29. typename ::boost::move_detail::disable_if_same<U, Foo, Foo&>::type
  30. operator=(const U& rhs)
  31. #else
  32. //->
  33. Foo& operator=(const U& rhs)
  34. //<-
  35. #endif
  36. //->
  37. { i = -rhs.i; return *this; } //(2)
  38. };
  39. //]
  40. struct Bar
  41. {
  42. int i;
  43. explicit Bar(int val) : i(val) {}
  44. };
  45. //<-
  46. #ifdef NDEBUG
  47. #undef NDEBUG
  48. #endif
  49. //->
  50. #include <cassert>
  51. int main()
  52. {
  53. //[template_assign_example_main
  54. Foo foo1(1);
  55. //<-
  56. assert(foo1.i == 1);
  57. //->
  58. Foo foo2(2);
  59. //<-
  60. assert(foo2.i == 2);
  61. Bar bar(3);
  62. assert(bar.i == 3);
  63. //->
  64. foo2 = foo1; // Calls (1) in C++11 but (2) in C++98
  65. //<-
  66. assert(foo2.i == 1);
  67. assert(foo1.i == 1); //Fails in C++98 unless workaround is applied
  68. foo1 = bar;
  69. assert(foo1.i == -3);
  70. foo2 = boost::move(foo1);
  71. assert(foo1.i == 0);
  72. assert(foo2.i == -3);
  73. //->
  74. const Foo foo5(5);
  75. foo2 = foo5; // Calls (1) in C++11 but (2) in C++98
  76. //<-
  77. assert(foo2.i == 5); //Fails in C++98 unless workaround is applied
  78. assert(foo5.i == 5);
  79. //->
  80. //]
  81. return 0;
  82. }
  83. #include <boost/move/detail/config_end.hpp>