Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<class _Ty> inline
- _Ty&& forward(typename identity<_Ty>::type& _Arg)
- { // forward _Arg, given explicitly specified type parameter
- return ((_Ty&&)_Arg);
- }
- template<typename T>
- T&& forward_with_deduction(T&& obj)
- {
- return static_cast<T&&>(obj);
- }
- void test(int&){}
- void test(const int&){}
- void test(int&&){}
- template<typename T>
- void perfect_forwarder(T&& obj)
- {
- test(forward_with_deduction(obj));
- }
- int main()
- {
- int x;
- const int& y(x);
- int&& z = std::move(x);
- test(forward_with_deduction(7)); // 7 is an int&&, correctly calls test(int&&)
- test(forward_with_deduction(z)); // z is treated as an int&, calls test(int&)
- // All the below call test(int&) or test(const int&) because in perfect_forwarder 'obj' is treated as
- // an int& or const int& (because it is named) so T in forward_with_deduction is deduced as int&
- // or const int&. The T&& in static_cast<T&&>(obj) then collapses to int& or const int& - which is not what
- // we want in the bottom two cases.
- perfect_forwarder(x);
- perfect_forwarder(y);
- perfect_forwarder(std::move(x));
- perfect_forwarder(std::move(y));
- }
- template<typename T>
- void
- f(T&& t)
- {
- std::forward(t);
- }
- template<typename U>
- U&&
- f(U&& u)
- { return u; }
- template<typename U>
- U&&
- f(U&& u)
- { return std::move(u); }
- template<typename T> T&& forward(T& x) {
- return static_cast<T&&>(x);
- }
- void somefunc( int& ){} // #1
- void somefunc( int&& ){} // #2
- template<typename T> void ForwardingFunc(T&& x) {
- somefunc(forward(x));
- }
- int main() {
- ForwardingFunc(5);
- }
- somefunc(forward(x));
- foo(x); // no implicit move
- bar(x); // else this would probably not do what you intend
- template<>
- int& forward(int& x)
- {
- return static_cast<int&>(x);
- }
Add Comment
Please, Sign In to add comment