fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <algorithm>
  5. #include <iomanip>
  6. #include <type_traits>
  7. #include <typeinfo>
  8. #ifndef _MSC_VER
  9. # include <cxxabi.h>
  10. #endif
  11. #include <memory>
  12. #include <string>
  13. #include <cstdlib>
  14.  
  15. template <class T>
  16. std::string
  17. type_name()
  18. {
  19. typedef typename std::remove_reference<T>::type TR;
  20. std::unique_ptr<char, void(*)(void*)> own
  21. (
  22. #ifndef _MSC_VER
  23. abi::__cxa_demangle(typeid(TR).name(), nullptr,
  24. nullptr, nullptr),
  25. #else
  26. nullptr,
  27. #endif
  28. std::free
  29. );
  30. std::string r = own != nullptr ? own.get() : typeid(TR).name();
  31. if (std::is_const<TR>::value)
  32. r += " const";
  33. if (std::is_volatile<TR>::value)
  34. r += " volatile";
  35. if (std::is_lvalue_reference<T>::value)
  36. r += "&";
  37. else if (std::is_rvalue_reference<T>::value)
  38. r += "&&";
  39. return r;
  40. }
  41.  
  42. template<typename T1, typename T2>
  43. struct my_tuple {
  44. T1 x;
  45. T2 y;
  46. my_tuple(const T1& x, const T2& y) : x(x), y(y) {
  47. std::cout << "tuple(" << type_name<const T1&>() << "," << type_name<const T2&>() << ")" << std::endl;
  48. }
  49. my_tuple(my_tuple<T1,T2>&& other) : x(other.x), y(other.y) {
  50. std::cout << "tuple(" << type_name<my_tuple<T1,T2>&&>() << ")" << std::endl;
  51. }
  52. my_tuple(const my_tuple<T1,T2>& other) : x(other.x), y(other.y) {
  53. std::cout << "tuple(" << type_name<const my_tuple<T1,T2>&>() << ")" << std::endl;
  54. }
  55. my_tuple& operator=(my_tuple<T1,T2>&& other) {
  56. std::cout << "tuple(" << type_name<my_tuple<T1,T2>&&>() << ")" << std::endl;
  57. x = other.x; y = other.y;
  58. }
  59. my_tuple& operator=(const my_tuple<T1,T2>& other) {
  60. std::cout << "tuple(" << type_name<const my_tuple<T1,T2>&>() << ")" << std::endl;
  61. x = other.x; y = other.y;
  62. }
  63. };
  64.  
  65. template<typename T1, typename T2>
  66. my_tuple<T1&, T2&> my_tie(T1& x, T2& y) {
  67. return my_tuple<T1&, T2&>(x,y);
  68. }
  69.  
  70.  
  71. struct Foo {
  72. int x, y;
  73.  
  74. Foo(int x, int y) : x(x), y(y) {
  75. std::cout << "Foo(x,y)" << std::endl;
  76. }
  77. ~Foo() {
  78. std::cout << "~Foo()" << std::endl;
  79. }
  80.  
  81. template<typename T1, typename T2>
  82. operator my_tuple<T1, T2>() {
  83. std::cout << "tuple conversion" << std::endl;
  84. return my_tuple<T1, T2>(x, y);
  85. }
  86. };
  87.  
  88. int main()
  89. {
  90. int a, b;
  91. my_tie(a, b) = Foo(3,4);
  92.  
  93. std::cout << a << ", " << b << std::endl;
  94.  
  95. return 0;
  96. }
  97.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Foo(x,y)
tuple conversion
tuple(int&,int&)
tuple(int&,int&)
tuple(my_tuple<int&, int&>&&)
~Foo()
3, 4