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?
_Remove_referenceis a template that, well, removes the reference from its type. I’m pretty sure that the template is specialized forT&andT&&with the sametypedef, right?Not sure how much I should go into details here. Are you familiar with template metaprogramming?
_Moveseems to do exactly whatstd::movedoes: it casts its argument to an rvalue. The point of the exercise is thatstd::swapcan do moves instead of copies. Are you familiar with move semantics?The term you are looking for is “rvalue reference”. Watch this video and come back with questions.