簡體   English   中英

為什么沒有_Remove_reference,std :: move()不起作用?

[英]Why does std::move() not work without _Remove_reference?

如你所知,_Remove_reference存在,將T&轉換為T或T &&轉換為T.

我以一種俏皮的心情制作了以下代碼,它完全不像我預期的那樣工作,但不知道為什么。

template<class _Ty>
struct _Remove_reference
{   // remove reference
    typedef _Ty _Type;
    static void func(){ cout << "1" << endl; } 
};

// template<class _Ty>
// struct _Remove_reference<_Ty&>
// {    // remove reference
//  typedef _Ty _Type;
//  static void func(){ cout << "2" << endl; }
// };
// 
// template<class _Ty>
// struct _Remove_reference<_Ty&&>
// {    // remove rvalue reference
//  typedef _Ty _Type;
//  static void func(){ cout << "3" << endl; }
// };

template<class _Ty> inline
    typename _Remove_reference<_Ty>::_Type&&
    move(_Ty&& _Arg)
{   // forward _Arg as movable
    typename _Remove_reference<_Ty>::func();
    return ((typename _Remove_reference<_Ty>::_Type&&)_Arg);
}

int main(){
    int a1= 3;
    int&& a2 = move(a1); // can't convert the a1 to int&&
    return 0;
}

我想這都是關於參考折疊規則和模板參數推導但我很困惑。 我對此的好奇心必須讓我睡不着覺。

提前致謝。

特定

template<class _Ty> inline
typename _Remove_reference<_Ty>::_Type&&
move(_Ty&& _Arg)

當你move(a1)_Ty被推斷為int& _Ty&&因此仍然是int&由於引用折疊規則,所以你需要刪除引用get int才能使它成為rvalue引用。

這是模板參數推導規則的特例。 如果你有一個函數參數是T&& ,其中T是一個模板參數,那么如果你將一個左值(即一個命名對象或一個左值引用)傳遞給函數,那么T推導為X&其中X是左值對象的類型。 如果將rvalue(臨時或右值引用)傳遞給函數,則T僅推導為X

例如, move(a1)推導_Tyint& ,而move(42)推導_Tyint

順便說一句:我猜你從編譯器的標准庫中獲取了這個代碼 - 用前導下划線和大寫字母裝飾的名稱_Like _這是為編譯器和標准庫實現保留的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM