为什么从右值整数向量的元素中推导 decltype(auto) 的类型是 int&?

Why type deduction of decltype(auto) from element of rvalue int vector is int&?

本文关键字:auto 类型 int decltype 整数 向量 为什么 元素      更新时间:2023-10-16

下面的代码结果是0100(符合CLang,GNU++14)。我期望 0001,因为 func 将 rvalue 向量作为参数,然后 forward(c)[0] 是 int 的常量引用,因此 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的重载。

可以更改[](具有返回值或右值的&&重载),但这样做可能会破坏现有代码。 因此,这可能至少要到std2才会发生,这允许在不破坏现有代码的情况下破坏std中的修订。