1

I'm subclassing std::optional and need to delete the operator==(bool) and implement my custom operator==(enum).

To delete the operator, this worked:

constexpr bool operator == ( bool ) noexcept = delete; 

Works great for the code below, throwing a "deleted function" compile error

OptionalSubclass<int> ReturnEvens( int i ) { if ( i % 2 == 0 ) return i; return {}; } : : auto result = ReturnEvens(42); if ( result == true ) std::cout << *result << " is even" << std::endl; 

However, the below code, with an implied 'true', compiles and executes

auto result = ReturnEvens(42); if ( result ) std::cout << *result << " is even" << std::endl; 

Is there a different operator I should be deleting?

4
  • What do You understand by "subclassing"? Commented Jul 26, 2019 at 16:14
  • 3
    Your function returns std::optional<int> rather than your new derived class. Is that deliberate? Commented Jul 26, 2019 at 16:16
  • Please edit your question to contain minimal reproducible example Commented Jul 26, 2019 at 17:11
  • @LightnessRacesinOrbit, thanks for catching my mistake. Fixed my OP. Commented Jul 26, 2019 at 19:03

1 Answer 1

6

std::optional has an operator bool() that allows it to be converted to a bool for evaluation in a condition. You need to delete that operator as well so it cannot be implicitly converted.

Sign up to request clarification or add additional context in comments.

8 Comments

OP seems to use std::optional instead of his subclass. If that is the case then your answer is wrong.
@Slava OP made a mistake, but it's clear that the return object is supposed to be the derived object, not optional<int>.
@Rakete1111 it is not clear to me. And why do we have rules if we ignore them?
@Slava They also say the the optional code in the first block is giving an error because the deleted the operator. So they are either modifying optional directly or just didn't want to show the derived class.
@NathanOliver they can say whatever. No minimal reproducible example - never happened. This suppose not only help OP but others who will come on relevant seacrh. And what do they see? You can disable std::optional operator
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.