問題描述
在 VS2010 中 std::forward 定義如下:
In VS2010 std::forward is defined as such:
template<class _Ty> inline
_Ty&& forward(typename identity<_Ty>::type& _Arg)
{ // forward _Arg, given explicitly specified type parameter
return ((_Ty&&)_Arg);
}
identity
似乎僅用于禁用模板參數(shù)推導(dǎo).在這種情況下故意禁用它有什么意義?
identity
appears to be used solely to disable template argument deduction. What's the point of purposefully disabling it in this case?
推薦答案
如果將 X
類型的對(duì)象的右值引用傳遞給采用 T&& 類型的模板函數(shù)
作為其參數(shù),模板參數(shù)推導(dǎo)推導(dǎo)出 T
為 X
.因此,參數(shù)的類型為 X&&
.如果函數(shù)參數(shù)是左值或 const 左值,則編譯器將其類型推導(dǎo)為該類型的左值引用或 const 左值引用.
If you pass an rvalue reference to an object of type X
to a template function that takes type T&&
as its parameter, template argument deduction deduces T
to be X
. Therefore, the parameter has type X&&
. If the function argument is an lvalue or const lvalue, the compiler deduces its type to be an lvalue reference or const lvalue reference of that type.
如果 std::forward
使用模板參數(shù)推導(dǎo):
If std::forward
used template argument deduction:
由于帶有名稱的對(duì)象是左值
,因此std::forward
唯一一次正確地轉(zhuǎn)換為T&&
參數(shù)是一個(gè)未命名的右值(如 7
或 func()
).在完美轉(zhuǎn)發(fā)的情況下,您傳遞給 std::forward
的 arg
是一個(gè)左值,因?yàn)樗幸粋€(gè)名稱.std::forward
的類型將被推導(dǎo)出為左值引用或常量左值引用.引用折疊規(guī)則將導(dǎo)致 std::forward 中 static_cast
T&&
始終解析為左值引用或常量左值引用.
Since objects with names are lvalues
the only time std::forward
would correctly cast to T&&
would be when the input argument was an unnamed rvalue (like 7
or func()
). In the case of perfect forwarding the arg
you pass to std::forward
is an lvalue because it has a name. std::forward
's type would be deduced as an lvalue reference or const lvalue reference. Reference collapsing rules would cause the T&&
in static_cast<T&&>(arg)
in std::forward to always resolve as an lvalue reference or const lvalue reference.
示例:
template<typename T>
T&& forward_with_deduction(T&& obj)
{
return static_cast<T&&>(obj);
}
void test(int&){}
void test(const int&){}
void test(int&&){}
template<typename T>
void perfect_forwarder(T&& obj)
{
test(forward_with_deduction(obj));
}
int main()
{
int x;
const int& y(x);
int&& z = std::move(x);
test(forward_with_deduction(7)); // 7 is an int&&, correctly calls test(int&&)
test(forward_with_deduction(z)); // z is treated as an int&, calls test(int&)
// All the below call test(int&) or test(const int&) because in perfect_forwarder 'obj' is treated as
// an int& or const int& (because it is named) so T in forward_with_deduction is deduced as int&
// or const int&. The T&& in static_cast<T&&>(obj) then collapses to int& or const int& - which is not what
// we want in the bottom two cases.
perfect_forwarder(x);
perfect_forwarder(y);
perfect_forwarder(std::move(x));
perfect_forwarder(std::move(y));
}
這篇關(guān)于為什么使用 std::forward 禁用模板參數(shù)推導(dǎo)?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!