gpt4 book ai didi

c++ - 返回时不允许隐式转换

转载 作者:行者123 更新时间:2023-12-01 08:52:28 25 4
gpt4 key购买 nike

#include <optional>

bool f() {
std::optional<int> opt;
return opt;
}

不编译: 'return': cannot convert from 'std::optional<int>' to 'bool'
咨询引用我本来想找到一个解释,但我读了它应该没问题。

Implicit conversions are performed whenever an expression of some type T1 is used in context that does not accept that type, but accepts some other type T2; in particular:

  • when the expression is used as the argument when calling a function that is declared with T2 as parameter;
  • when the expression is used as an operand with an operator that expects T2;
  • when initializing a new object of type T2, including return statement in a function returning T2;
  • when the expression is used in a switch statement (T2 is integral type);
  • when the expression is used in an if statement or a loop (T2 is bool).

最佳答案

std::optional没有任何隐式转换为 bool 的工具. (允许隐式转换为 bool 通常被认为是一个坏主意,因为 bool 是一个整数类型,所以像 int i = opt 这样的东西会编译并做完全错误的事情。)
std::optional确实有一个“上下文转换”到 bool,其定义看起来类似于强制转换运算符:explicit operator bool() .这不能用于隐式转换;它仅适用于某些特定情况,其中预期的“上下文”是 bool 值,例如 if 语句的条件。

您要的是opt.has_value() .

关于c++ - 返回时不允许隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60224716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com