In the simple following example, I expected the output would be "2222". But the actual output was "2122" for both VC++ 11.0 and g++ 4.6.1.
#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;
}
I disassembled and found that the first func call, func((int &)x), uses func<int> instead of func<int &>. Why and how is this happened?
Template type argument deduction works that way. The cast to int&
has no effect, as the variable x
is already an lvalue. Template type deduction when the argument is an lvalue and the parameter is not a reference will deduce the type not to be a reference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.