局部变量的引用折叠

reference collapsing for local variables

本文关键字:折叠 引用 局部变量      更新时间:2023-10-16

T上参数化的函数模板中,类型T&&可能是也可能不是右值引用,这取决于参数的值类别:

template <typename T>
void function(T&& x)
{
    // ...
}
std::string some_named_string;
function(some_named_string);       // T&& is std::string&
function(std::string("hello"));    // T&& is std::string&&

同样的规则是否也适用于自动推断类型的局部变量?

auto&& x = some_named_string;      // is x a std::string& here?
auto&& y = std::string("hello");   // is y a std::string&& here?

是。auto恰好被指定为模板参数推导。