[英]C++ template implicit instantiation with reference parameter
在下面的簡單示例中,我預計輸出將為“2222”。 但VC ++ 11.0和g ++ 4.6.1的實際輸出為“2122”。
#include <iostream>
template <class T>
void func(T x)
{
x = 2;
std::cout << x;
}
int main()
{
int x = 1;
func((int &)x);
std::cout << x;
func<int &>(x);
std::cout << x;
return 0;
}
我反匯編並發現第一個func調用func((int&)x)使用func <int>而不是func <int&>。 為什么以及如何發生這種情況?
模板類型參數推導以這種方式工作。 由於變量x
已經是左值,因此轉換為int&
並且沒有效果。 當參數是左值且參數不是引用時的模板類型推導將推斷出類型不是引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.