为什么从右值整数向量的元素中推导 decltype(auto) 的类型是 int&?
Why type deduction of decltype(auto) from element of rvalue int vector is int&?
下面的代码结果是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
中的修订。
相关文章:
- 推理类型如何工作"auto"和按引用调用?
- 将函数参数类型声明为 auto
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 使用"auto"推断嵌套初始值设定项列表的类型
- "auto"推断出 hashtable_policy.h 中的错误类型
- 为什么"const auto [x, y]"绑定到引用类型时没有按预期运行?
- 对'auto'扣除类型的困惑
- 如果使用返回引用的函数初始化"auto"var,为什么它不声明引用类型?
- decltype(auto) 是否使尾随返回类型过时?
- 用 decltype 和 auto 推导出 const(返回)类型
- 警告:函数使用不带尾随返回类型的'auto'类型说明符
- 在 Objective-C++ 中应用于__weak指针时,通过关键字推导类型"auto"规则是什么?
- decltype(auto) 类型演绎:返回 x 与返回 (x)
- 在 c++11 中,指针的"auto"类型赋值是否需要"*"?
- 警告:'auto'类型说明符是 C++11 扩展 [-WC++11-扩展]
- C++ : const int * 和 cont int & 之间的 auto 类型不同的扣除
- "auto"类型推导编译,而显式类型给出错误
- c++ 0X中auto类型的求值
- 使用'auto'类型推导 - 如何找出编译器推导出的类型?
- 错误:无法推断'auto'类型(需要初始值设定项)