![](/img/trans.png)
[英]how to tell auto to deduce a non reference type for element of vector<bool>
[英]How reference deduce works?
可以復制到此 。
我讀了《 有效的現代C ++》 。 在Item 1
下,我找到了一個可供普遍參考的案例:
對於最后一個例子, f(27);
我在VS2013下進行了測試。
void process(int& x)
{
std::cout << "int&" << std::endl;
}
void process(int&& x)
{
std::cout << "int&&" << std::endl;
}
template<typename T>
void f(T&& param)
{
std::cout << "------------------------------------------------" << std::endl;
if (std::is_lvalue_reference<T>::value)
{
std::cout << "T is lvalue reference" << std::endl;
}
else if (std::is_rvalue_reference<T>::value)
{
std::cout << "T is rvalue reference" << std::endl;
}
else
{
std::cout << "T is NOT lvalue reference" << std::endl;
}
std::cout << "param is: " << typeid(param).name() << std::endl;
process(std::forward<T>(param));
process(param);
}
int getINT()
{
int x = 10;
return x;
}
int _tmain(int argc, _TCHAR* argv[])
{
f(10);
f(getINT());
return 0;
}
這是輸出:
------------------------------------------------
T is NOT lvalue reference
param is: int
int&&
int&
------------------------------------------------
T is NOT lvalue reference
param is: int
int&&
int&
我發現在沒有std::forward<T>(param)
的模板函數中,將調用process(int& x)
但根據本書, param
的類型應為右值引用,因此process(int&& x)
應為叫做。 但這種情況並非如此。 我誤會了嗎?
這是我從其他線程找到的轉發參考:
您正在將類型與值類別混淆。 作為命名參數, param
是一個左值,然后對於process(param);
process(int& x)
將被調用。
這就是為什么我們應該在轉發參考中使用std::forward
; 在這種情況下, std::forward<T>(param)
將param
轉換為rvalue,然后將調用process(int&& x)
(如預期的那樣)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.