Guest User

Untitled

a guest
Dec 18th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. template<class _Ty> inline
  2. _Ty&& forward(typename identity<_Ty>::type& _Arg)
  3. { // forward _Arg, given explicitly specified type parameter
  4. return ((_Ty&&)_Arg);
  5. }
  6.  
  7. template<typename T>
  8. T&& forward_with_deduction(T&& obj)
  9. {
  10. return static_cast<T&&>(obj);
  11. }
  12.  
  13. void test(int&){}
  14. void test(const int&){}
  15. void test(int&&){}
  16.  
  17. template<typename T>
  18. void perfect_forwarder(T&& obj)
  19. {
  20. test(forward_with_deduction(obj));
  21. }
  22.  
  23. int main()
  24. {
  25. int x;
  26. const int& y(x);
  27. int&& z = std::move(x);
  28.  
  29. test(forward_with_deduction(7)); // 7 is an int&&, correctly calls test(int&&)
  30. test(forward_with_deduction(z)); // z is treated as an int&, calls test(int&)
  31.  
  32. // All the below call test(int&) or test(const int&) because in perfect_forwarder 'obj' is treated as
  33. // an int& or const int& (because it is named) so T in forward_with_deduction is deduced as int&
  34. // or const int&. The T&& in static_cast<T&&>(obj) then collapses to int& or const int& - which is not what
  35. // we want in the bottom two cases.
  36. perfect_forwarder(x);
  37. perfect_forwarder(y);
  38. perfect_forwarder(std::move(x));
  39. perfect_forwarder(std::move(y));
  40. }
  41.  
  42. template<typename T>
  43. void
  44. f(T&& t)
  45. {
  46. std::forward(t);
  47. }
  48.  
  49. template<typename U>
  50. U&&
  51. f(U&& u)
  52. { return u; }
  53.  
  54. template<typename U>
  55. U&&
  56. f(U&& u)
  57. { return std::move(u); }
  58.  
  59. template<typename T> T&& forward(T& x) {
  60. return static_cast<T&&>(x);
  61. }
  62.  
  63. void somefunc( int& ){} // #1
  64. void somefunc( int&& ){} // #2
  65.  
  66. template<typename T> void ForwardingFunc(T&& x) {
  67. somefunc(forward(x));
  68. }
  69.  
  70. int main() {
  71. ForwardingFunc(5);
  72. }
  73.  
  74. somefunc(forward(x));
  75.  
  76. foo(x); // no implicit move
  77. bar(x); // else this would probably not do what you intend
  78.  
  79. template<>
  80. int& forward(int& x)
  81. {
  82. return static_cast<int&>(x);
  83. }
Add Comment
Please, Sign In to add comment