下面的代码Result0100(符合CLang,GNU++14)。我希望是0001,因为func使用右值向量作为参数,那么forward(c)是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发布于 2017-01-14 07:03:22
c是一个右值引用。
[]具有const和非const重载。当传递vector<T,A>&&类型的向量时,所选的重载是非const类型的重载。
可以更改[] (使其具有返回值或右值的&&重载),但这样做可能会破坏现有代码。因此,这可能至少在std2之前不会发生,它允许在不破坏现有代码的情况下破坏std中的修订。
https://stackoverflow.com/questions/41644717
复制相似问题