fork download
  1. #include <algorithm>
  2. #include <iostream>
  3.  
  4. template <typename T>
  5. struct A {
  6.  
  7. A(std::size_t size)
  8. : size_(size),
  9. t_(new T[size]) {
  10. }
  11.  
  12. ~A() {
  13. delete[] t_;
  14. }
  15.  
  16. A(const A &a) {
  17. t_ = new T[a.size_];
  18. std::copy(a.t_, a.t_ + a.size_, t_);
  19. }
  20.  
  21. A(A &&a) {
  22. t_ = a.t_;
  23. size_ = a.size_;
  24.  
  25. a.t_ = 0;
  26. }
  27.  
  28. A& operator = (A a) {
  29. // unified assignment operator, only need one assignment operator
  30. // If the value is passed as rvalue, the move ctor will be invoked
  31. // If the value is passed as lvalue, the copy ctor will be invoked
  32. swap(*this, a);
  33. return *this;
  34. }
  35.  
  36. T& operator [](size_t element) {
  37. return t_[element];
  38. }
  39.  
  40. const T& operator[](size_t element) const {
  41. return t_[element];
  42. }
  43.  
  44. size_t size() {
  45. return size_;
  46. }
  47.  
  48. private:
  49.  
  50. friend void swap(A &first, A &second) {
  51. // custom swap function, used to reduce code duplication
  52. std::swap(first.t_,second.t_);
  53. std::swap(first.size_, second.size_);
  54. }
  55.  
  56. T *t_;
  57. std::size_t size_;
  58. };
  59.  
  60. template <typename T>
  61. struct B {
  62.  
  63. B(A<T> a1, A<T> a2)
  64. : a1_(a1),
  65. a2_(a2) {
  66.  
  67. }
  68.  
  69. B(const B& b)
  70. : a1_(b.a1_),
  71. a2_(b.a2_) {
  72.  
  73. }
  74.  
  75. B(B && b)
  76. : a1_(std::move(b.a1_)),
  77. a2_(std::move(b.a2_)) {
  78.  
  79. }
  80.  
  81. B& operator = (B b) {
  82. // unified assignment operator, only need one assignment operator
  83. // If the value is passed as rvalue, the move ctor will be invoked
  84. // If the value is passed as lvalue, the copy ctor will be invoked
  85. swap(*this, b);
  86. return *this;
  87. }
  88.  
  89. private:
  90.  
  91. friend void swap(B &first, B& second) {
  92. std::swap(first.a1_, second.a1_);
  93. std::swap(first.a2_, second.a2_);
  94. }
  95.  
  96. A<T> a1_;
  97. A<T> a2_;
  98.  
  99. };
  100.  
  101. int main() {
  102. A<int> c(3);
  103. B<int> d(c, c);
  104. swap(d, c);
  105. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'int main()':
prog.cpp:104:14: error: no matching function for call to 'swap(B<int>&, A<int>&)'
prog.cpp:91:14: note: candidates are: void swap(B<int>&, B<int>&)
prog.cpp:50:14: note:                 void swap(A<int>&, A<int>&)
stdout
Standard output is empty