C++ 编译器说 "inconsistent deduction for auto return type"

标签 c++ auto reinterpret-cast nullptr stdoptional

C++ 中有一个很好的特性,您可以说该函数的返回类型为“auto”,编译器会找出它。但是,如果我在出错时返回一个指针和 nullptr 怎么办?不知何故,编译器无法推断出正确的类型并给出错误。

在下面的简单示例中想象 std::vector<int>计划在未来完全被其他东西取代,以证明在这里使用 auto 是合理的:

#include<vector>
std::vector<int> e;
auto test(){
  if(!e.empty())
    return &e[0];
  return nullptr;
}

在 c++17 中,我收到以上错误消息。

所以我尝试用

替换最后一次返回

return reinterpret_cast<decltype(&e[0])>(nullptr)

并得到错误invalid cast .我看到的唯一解决方案是用 3 行替换该返回:

auto out=&e[0];
out=nullptr;
return out;

我可能可以通过替换 auto 将其减少到 2 行用某种 decltype ,但我想其他类型的转换可以在一行中做我想做的事吗? 还是我需要为这种情况使用更新版本的 c++ 标准?

我还尝试了 std::make_optional 并遇到了同样的问题,nullopt_t 的类型与 std::optional 不同。 我真正喜欢的是编译器是否会自动将类型推断为 std::optional无论如何...

最佳答案

只退一次。

auto test() {
  return e.empty() ? nullptr : &e[0];
}

you should explain the issue with OPs code

有两个不同类型的返回。选择哪种类型?

and why this fixes it – 463035818_is_not_a_number

因为有超长的规则,条件运算符的结果是什么类型。参见 https://en.cppreference.com/w/cpp/language/operator_other#Conditional_operator

关于C++ 编译器说 "inconsistent deduction for auto return type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75267360/

相关文章:

c++ - C++模板和参数化的Google测试

C++11 将 `auto` Lambda 更改为不同的 Lambda?

c++ - 这是reinterpret_cast 的合法使用吗?如果不是,我该怎么做?

c++ - 为什么我需要 reinterpret_cast 将 Fred ** const 转换为 void ** const?

c++ - 电子游戏编程中的数学

c++ - CMake:处理共享库与静态库的链接

c++ - 如何判断段错误?

c++ - 当在 C++11 中使用带有两个声明的 auto 时会发生什么?

c++ - 为什么在使用STL列表时不能使用此回文功能?

c++ - 这是什么 reinterpret_cast 约定?它比 static_cast 好吗?