我正在寫這段代碼
#include <iostream>
#include <string>
template <typename T>
void Print(T& value)
{
std::cout << value << std::endl;
}
int main()
{
Print("Hello");
Print(1);
}
并且在編譯時,編譯器告訴一個錯誤“ void Print<int>(T &)' : cannot convert argument 1 from 'int' to 'T &'”。但是Print("Hello")沒有得到錯誤。這是為什么呢?
我將Print()功能更改為
void Print(T value)
{
std::cout << value << std::endl;
}
有效。但我不明白為什么以前的代碼不起作用。
uj5u.com熱心網友回復:
情況1
在這里,我們考慮如何Print(1);作業。
在這種情況下,問題在于它1是一個右值,而您正試圖將該右值系結到對 nonconstT(即T&)的左值參考,這是不可能的,因此會出現錯誤。例如,您不能擁有:
void Print(int &value)
{
std::cout << value << std::endl;
}
int main()
{
Print(1);// won't work
}
解決方案
因此,要解決您的問題,您可以使用對可以系結到右值的 const (即)的左值參考Tconst T&,如下所示:
template <typename T>
void Print(const T& value)//note the const added here
{
std::cout << value << std::endl;
}
int main()
{
Print(1); //works now
}
或者,您也可以將引數作為對 nonconstT(即T&&)的右值參考。
template <typename T>
void Print(T&& value)//note the && added here
{
std::cout << value << std::endl;
}
int main()
{
Print(1); //this works too
}
案例2
這里我們考慮陳述句 Print("Hello");
在這種情況下,"Hello"是一個字串文字并且具有型別const char [6]。此外,字串文字"Hello"是左值。
而且我們知道我們可以將左值系結到對非constT(即T&)的左值參考。所以在這種情況下沒有錯誤。另請注意,在這種情況下,T推匯出為const char [6]。
筆記
在上面的情況 2 ( Print("Hello");) 中,沒有型別衰減,因為引數是通過參考而不是值傳遞的。
uj5u.com熱心網友回復:
因為這:
test.cpp:45:11: error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'
45 | Print(1);
| ^
因此,將其轉換為通用參考:
template <typename T>
void Print( T&& value ) // notice &&, that's a universal reference, not an rvalue ref
{
std::cout << value << std::endl;
}
uj5u.com熱心網友回復:
1是一個右值,因此不能系結到T&. 它可以系結到const T&。
那是,
void Print(const T& value)
或者
void Print(T&& value)
是修復。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/415741.html
標籤:
