std::forward--完美转发

  1. std::forward<T>(u)有两个参数:T与u.当T为左值引用类型时,u将被转换为T类型的左值,否则u将被转换为T类型右值。如此定义std::forward是为了在使用右值引用参数的函数模板中解决参数的完美转发问题,提升了效率。
  2. 代码如下:
    template<class _Ty> inline
    	constexpr _Ty&& forward(
    		typename remove_reference<_Ty>::type& _Arg) _NOEXCEPT
    	{	// forward an lvalue as either an lvalue or an rvalue
    	return (static_cast<_Ty&&>(_Arg));
    	}
    
    template<class _Ty> inline
    	constexpr _Ty&& forward(
    		typename remove_reference<_Ty>::type&& _Arg) _NOEXCEPT
    	{	// forward an rvalue as an rvalue
    	static_assert(!is_lvalue_reference<_Ty>::value, "bad forward call");
    	return (static_cast<_Ty&&>(_Arg));
    	}
  3. 右值通过右值引用接受以后会转为左值,这个时候就用到std::forward
发布了51 篇原创文章 · 获赞 2 · 访问量 860

猜你喜欢

转载自blog.csdn.net/YRC333/article/details/98876068
今日推荐