Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion not allowed on return

Tags:

#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).
like image 753
darune Avatar asked Feb 14 '20 10:02

darune


People also ask

How do you avoid implicit conversions in SQL Server?

However to avoid having multiple plans in cache for int , smallint , tinyint and get rid of the implicit cast you could explicitly parameterize the query yourself - with a parameter of datatype int rather than having it be parameterized automatically.

How do you prevent implicit conversions in C++?

Keyword explicit tells compiler to not use the constructor for implicit conversion. For example declaring Bar's constructor explicit as - explicit Bar(int i); - would prevent us from calling ProcessBar as - ProcessBar(10); .

What is a implicit conversion?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.

What two commands will perform implicit conversion?

What two commands will perform implicit conversion? Answer: Cast and Convert.


1 Answers

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

like image 117
Sneftel Avatar answered Sep 20 '22 15:09

Sneftel