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/