voidan_orther_fun(int a, int& b) { std::cout << "in an_orther_fun(): a = " << a << ", b = " << ++b << std::endl; }
voidtransmit(int a, int b) { an_orther_fun(a, b); }
intmain() { int a = 2, b = 3;
std::cout << " before transmit(): a = " << a << ", b = " << b << std::endl; transmit(a, b); std::cout << " after transmit(): a = " << a << ", b = " << b << std::endl; return0; }
其输出为:
1 2 3
before transmit(): a = 2, b = 3 in an_orther_fun(): a = 2, b = 4 after transmit(): a = 2, b = 3
voidan_orther_fun(int a, int&& b) { std::cout << "in an_orther_fun(): a = " << a << ", b = " << b << std::endl; }
voidtransmit(int a, int&& b) { an_orther_fun(a, b); // error: cannot bind rvalue reference of type ‘int&&’ to lvalue of type ‘int’ }
intmain() { int a = 2;
std::cout << " before transmit(): a = " << a << ", b = " << b << std::endl; transmit(a, 3); std::cout << " after transmit(): a = " << a << ", b = " << b << std::endl; return0; }
/** * @brief Forward an lvalue. * @return The parameter cast to the specified type. * * This function is used to implement "perfect forwarding". */ template<typename _Tp> constexpr _Tp&& forward(typename std::remove_reference<_Tp>::type& __t)noexcept { returnstatic_cast<_Tp&&>(__t); }
/** * @brief Forward an rvalue. * @return The parameter cast to the specified type. * * This function is used to implement "perfect forwarding". */ template<typename _Tp> constexpr _Tp&& forward(typename std::remove_reference<_Tp>::type&& __t)noexcept { static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument" " substituting _Tp is an lvalue reference type"); returnstatic_cast<_Tp&&>(__t); }
std::cout << " before transmit(): a = " << a << ", b = " << b << std::endl; transmit(an_orther_fun, a, b); std::cout << " after transmit(): a = " << a << ", b = " << b << std::endl; return0; }
输出:
1 2 3
before transmit(): a =2, b = 3 in an_orther_fun(): a = 2, b = 4 after transmit(): a = 2, b = 4