简体   繁体   English

参考推导如何工作?

[英]How reference deduce works?

May be duplicated to this . 可以复制到此

I read Effective Modern C++ . 我读了《 有效的现代C ++》 Under Item 1 , I found a case for universal reference: Item 1下,我找到了一个可供普遍参考的案例: 在此处输入图片说明

For the last example f(27); 对于最后一个例子, f(27); I did a test under VS2013. 我在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. 我发现在没有std::forward<T>(param)的模板函数中,将调用process(int& x)但根据本书, param的类型应为右值引用,因此process(int&& x)应为叫做。 But this is not the case. 但这种情况并非如此。 Is it I misunderstand something? 我误会了吗?

Here is the forwarding reference I found from other thread : 这是我从其他线程找到的转发参考: 在此处输入图片说明

You're confusing types with value categories . 您正在将类型与值类别混淆。 As a named parameter, param is an lvalue, then for process(param); 作为命名参数, param是一个左值,然后对于process(param); process(int& x) will be called. process(int& x)将被调用。

That's why we should use std::forward with forwarding reference ; 这就是为什么我们应该在转发参考中使用std::forward std::forward<T>(param) converts param to rvalue for this case, then process(int&& x) will be called (as expected). 在这种情况下, std::forward<T>(param)param转换为rvalue,然后将调用process(int&& x) (如预期的那样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM