Implicit conversion not allowed on return

darune :
#include <optional>

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

Does not compile: '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.

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).
Sneftel :

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 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.

What you want is opt.has_value().

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29297&siteId=1