开发者

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

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 <algori开发者_Python百科thm>)
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?


_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.


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; };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜