Understanding std::swap(). What is the purpose of tr1::_Remove_reference?

蹲街弑〆低调 提交于 2020-01-04 05:36:11

问题


In the STL implementation of VS10 there is the following code for a variant of std::swap():

    // TEMPLATE FUNCTION _Move
template<class _Ty> inline
    typename tr1::_Remove_reference<_Ty>::_Type&&
        _Move(_Ty&& _Arg)
    {   // forward _Arg as movable
    return ((typename tr1::_Remove_reference<_Ty>::_Type&&)_Arg);
    }

    // TEMPLATE FUNCTION swap (from <algorithm>)
template<class _Ty> inline
    void swap(_Ty& _Left, _Ty& _Right)
    {   // exchange values stored at _Left and _Right
    _Ty _Tmp = _Move(_Left);
    _Left = _Move(_Right);
    _Right = _Move(_Tmp);
    }

The cast to (typename tr1::_Remove_reference<_Ty>::_Type&&) in _Move() is the source of my question.

In this context _Remove_reference is defined as follows:

        // TEMPLATE _Remove_reference
template<class _Ty>
    struct _Remove_reference
    {   // remove reference
    typedef _Ty _Type;
    };

What does _Remove_reference do, and why? Furthermore, what does && do here, and how is it termed?


回答1:


_Remove_reference is a template that, well, removes the reference from its type. I'm pretty sure that the template is specialized for T& and T&& with the same typedef, right?

Not sure how much I should go into details here. Are you familiar with template metaprogramming?

_Move seems to do exactly what std::move does: it casts its argument to an rvalue. The point of the exercise is that std::swap can do moves instead of copies. Are you familiar with move semantics?

what does && do here, and how is it termed?

The term you are looking for is "rvalue reference". Watch this video and come back with questions.




回答2:


This is a part of C++0x rvalue references. What the template move does is convert a reference to a rvalue reference so that swap can be implemented with move semantics (no copies are made if the type supports moving.

The _Remove_reference looks like a template that is there to extract a type that has no reference from a type that might have it.

template <typename T> struct remove_ref { typedef T type; };
template <typename T> struct remove_ref<T&> { typedef T type; };


来源:https://stackoverflow.com/questions/4820643/understanding-stdswap-what-is-the-purpose-of-tr1-remove-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!