从自动输入参数推导返回类型

deducing return type from auto input argument

本文关键字:返回类型 参数 输入      更新时间:2023-10-16

为什么下面的代码编译失败?编译器不能从输入推断返回类型吗?

不要完全跟随显示的类型转换错误。

auto func(auto &x)
{
 return x[0];
}
int main()
{
  vector<int> v = { 1, 2, 3};
  (void)func(v);
}
$ g++ -std=c++1z auto.cc 
auto.cc: In instantiation of ‘auto func(auto:1&) [with auto:1 = std::vector<int>]’:
auto.cc:15:16:   required from here
auto.cc:8:14: error: could not convert ‘(& x)->std::vector<_Tp, _Alloc>::operator[]<int, std::allocator<int> >(0ul)’ from ‘__gnu_cxx::__alloc_traits<std::allocator<int> >::value_type {aka int}’ to ‘std::vector<int>’
    return x[0];

auto作为函数参数类型不是标准的c++ 。然而,g++ 7 (svn)接受了……