为什么从右值 int 向量的元素中 decltype(auto) 的类型推导是 int&?
Why type deduction of decltype(auto) from element of rvalue int vector is int&?
以下代码结果为 0100(符合 CLang、GNU++14)。我期望 0001,因为 func 将右值向量作为参数,然后 forward(c)[0] 是 int 的 const 引用,因此 decltype(auto) 的类型推导应该导致 const int&。请帮助我了解结果。谢谢!
template <typename T>
decltype(auto) func(T&& c)
{
return forward<T>(c)[0];
}
int main(int argc, const char * argv[])
{
cout
<< is_same< int, decltype(func(vector<int>{3}))>::value
<< is_same< int&, decltype(func(vector<int>{3}))>::value
<< is_same< const int, decltype(func(vector<int>{3}))>::value
<< is_same< const int&, decltype(func(vector<int>{3}))>::value
<< endl;
return 0;
}
输出:
0100
c
是右值引用。
[]
有一个 const
和非 const
重载。当传递 vector<T,A>&&
类型的向量时,选择的重载是非 const
类型的向量。
[]
可以更改(使 &&
重载 returns 一个值或右值),但这样做可能会破坏现有代码。所以这可能至少要到 std2
才会发生,这允许在不破坏现有代码的情况下破坏 std
中的修订。
以下代码结果为 0100(符合 CLang、GNU++14)。我期望 0001,因为 func 将右值向量作为参数,然后 forward(c)[0] 是 int 的 const 引用,因此 decltype(auto) 的类型推导应该导致 const int&。请帮助我了解结果。谢谢!
template <typename T>
decltype(auto) func(T&& c)
{
return forward<T>(c)[0];
}
int main(int argc, const char * argv[])
{
cout
<< is_same< int, decltype(func(vector<int>{3}))>::value
<< is_same< int&, decltype(func(vector<int>{3}))>::value
<< is_same< const int, decltype(func(vector<int>{3}))>::value
<< is_same< const int&, decltype(func(vector<int>{3}))>::value
<< endl;
return 0;
}
输出:
0100
c
是右值引用。
[]
有一个 const
和非 const
重载。当传递 vector<T,A>&&
类型的向量时,选择的重载是非 const
类型的向量。
[]
可以更改(使 &&
重载 returns 一个值或右值),但这样做可能会破坏现有代码。所以这可能至少要到 std2
才会发生,这允许在不破坏现有代码的情况下破坏 std
中的修订。