Unused
Unused

Reputation: 195

C++ template implicit instantiation with reference parameter

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?

Upvotes: 4

Views: 172

Answers (1)

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.

Upvotes: 4

Related Questions