不允许在返回时进行隐式转换 [英] Implicit conversion not allowed on return

查看:114
本文介绍了不允许在返回时进行隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <optional>

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

不编译:'return': cannot convert from 'std::optional<int>' to 'bool'

咨询性参考文献,我原本想找到一个解释,但我认为应该没问题.

Consulting reference I would have thought to find an explanation, but I read it as it should be ok.

每当某种类型的表达式执行隐式转换 T1用于不接受该类型但接受某些类型的上下文中 其他类型T2;特别是:

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:

  • 当调用以T2作为参数声明的函数时,将表达式用作自变量时;
  • 当表达式用作期望T2的运算符的操作数时;
  • 初始化类型为T2的新对象时,包括返回T2的函数中的return语句;
  • 在switch语句中使用表达式时(T2是整数类型);
  • 在if语句或循环(T2为bool)中使用表达式时.
  • 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 doesn't have any facility for implicitly converting to bool. (Allowing implicit conversions to bool is generally considered a bad idea, since bool is an integral type so something like int i = opt would compile and do completely the wrong thing.)

std::optional 确实具有向bool的上下文转换",其定义类似于强制转换运算符:explicit operator bool().这不能用于隐式转换.它仅适用于预期的上下文"是布尔值的某些特定情况,例如if语句的条件.

std::optional does have a "contextual conversion" to bool, the definition of which looks similar to a cast operator: explicit operator bool(). This cannot be used for implicit conversions; it only applies in certain specific situations where the expected "context" is a boolean one, like the condition of an if-statement.

您想要的是opt.has_value().

这篇关于不允许在返回时进行隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆