簡體   English   中英

編譯器如何知道必須調用std :: forward函數的哪個重載?

[英]How does the compiler know that which overload of std::forward function has to be called?

以下簽名聲明為std::forward overloads:

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

現在,考慮以下模板函數:

template<class T> T&& foo_as_always(T&& t)
{
    return std::forward<T>(t);
}

如果我寫:

int i = 0;
foo_as_always(i);

然后這就是編譯器如何使用T = int&實例化foo_as_always

int& foo_as_always(int& t)
{
    // Does it call the first signature of std::forward(int&)
    return std::forward<int&>(t);
}

如果我寫:

foo_as_always(0);

然后編譯器使用T = int實例化foo_as_always

int&& foo_as_always(int&& t)
{
    // Does it call the second signature of std::forward(int&&)?
    return std::forward<int>(t);
}

在這兩種情況下, t變量在任何表達式中都是l值。 編譯器如何知道必須調用std::forward函數的哪個重載?

因為你明確地提供了模板參數(你提供的是<T> ); 沒有類型扣除。

在調用foo_as_always(i); i是一個左值,所以T推導為int & ,這就是你為std::forward

在調用foo_as_always(0); 0是一個rvalue,因此T推導為int ,這也是你為std::forward

在這兩種情況下,它最終都會調用第一個重載,當然,因為t是左值,正如你所說的那樣。 但返回類型不同 - 在第一種情況下,它是int& && ,所以int& ,在第二種情況下,它是int &&

暫無
暫無

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

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