Search code examples
c++c++11rvalue-referenceeffective-c++forward-reference

How reference deduce works?


May be duplicated to this.

I read Effective Modern C++. Under Item 1, I found a case for universal reference:enter image description here

For the last example f(27); I did a test under 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;

}

Here is the output:

------------------------------------------------
T is NOT lvalue reference
param is: int
int&&
int&
------------------------------------------------
T is NOT lvalue reference
param is: int
int&&
int&

I found that within the template function, without std::forward<T>(param), process(int& x) will be called but according to the book, the type for param should be rvalue reference, so process(int&& x) should be called. But this is not the case. Is it I misunderstand something?

Here is the forwarding reference I found from other thread: enter image description here


Solution

  • You're confusing types with value categories. As a named parameter, param is an lvalue, then for process(param); process(int& x) will be called.

    That's why we should use std::forward with forwarding reference; std::forward<T>(param) converts param to rvalue for this case, then process(int&& x) will be called (as expected).