加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 使用通用引用实现转发功能

发布时间:2020-12-16 09:52:29 所属栏目:百科 来源:网络整理
导读:VS2013中std :: forward的实现是 templateclass _Ty inline _Ty forward(typename remove_reference_Ty::type _Arg) { // forward an lvalue return (static_cast_Ty(_Arg)); }templateclass _Ty inline _Ty forward(typename remove_reference_Ty::type _Ar
VS2013中std :: forward的实现是

template<class _Ty> inline
    _Ty&& forward(typename remove_reference<_Ty>::type& _Arg)
    {   // forward an lvalue
    return (static_cast<_Ty&&>(_Arg));
    }

template<class _Ty> inline
    _Ty&& forward(typename remove_reference<_Ty>::type&& _Arg) _NOEXCEPT
    {   // forward anything
    static_assert(!is_lvalue_reference<_Ty>::value,"bad forward call");
    return (static_cast<_Ty&&>(_Arg));
    }

左值参考的一个版本,右值参考的一个版本.为什么不对rvalue和lvalue引用使用通用引用:

template <typename T,typename U>
T&& Forward(U&& arg) {
  return static_cast<T&&>(arg);
}

解决方法

您的版本不符合标准,因为如果T是l值引用,则在rvalue上调用时,std :: forward是不需要编译的.来自[前进]:

template <class T> T&& forward(typename remove_reference<T>::type& t) noexcept;
template <class T> T&& forward(typename remove_reference<T>::type&& t) noexcept;

2 Returns: static_cast<T&&>(t).

3 if the second form is instantiated with an lvalue reference type,the program is ill-formed.

以这种方式定义std :: forward以确保std :: forward的(某些)滥用不会编译.有关更多讨论,请参阅n2951(尽管即使n2951也不使用此确切形式).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读