Make scoped enums contextually convertible to bool?

126 views
Skip to first unread message

Ivan G.

unread,
Oct 5, 2018, 7:45:29 AM10/5/18
to ISO C++ Standard - Future Proposals
This seems useful to test bits in "bitset" scoped enums (with proper overloaded operators).

But it asks only about underlying bool type for some reason. Maybe there are more of them.
Contextual conversion to bool would compare the underlying value with zero.

The problems with workarounds:
1) Overloading !, &&, or || is considered a bad practice and is still incomplete.
2) Overloading unary + seems even worse, because it breaks expectations.
3) Writing a function seems better, but is too verbose.
4) Overload a & to return a class which converts both to bool (contextually) and the enum value. May break expectations too because it doesn't return an enum class directly.

Unfortunately, allowing contextual bool conversion by default seems dangerous too - the simplest enum use case just lists various values but doesn't assume that [first] one which equals to zero is anything special.

Maybe there is a proposal somewhere to allow declaring conversion operators as global ones? So the programmer could specify a desired behaviour directly.

Zhihao Yuan

unread,
Oct 5, 2018, 4:08:25 PM10/5/18
to std-pr...@isocpp.org

Comparing to zero is not always the behavior you
want.  I seriously consider that scoped enum should
support member functions, so that you can write
a “explicit operator bool()” by yourself.

 

--
Zhihao Yuan, ID lichray
The best way to predict the future is to invent it.
_______________________________________________

Matthew Fioravante

unread,
Oct 5, 2018, 6:57:44 PM10/5/18
to ISO C++ Standard - Future Proposals, z...@miator.net


On Friday, October 5, 2018 at 4:08:25 PM UTC-4, Zhihao Yuan wrote:

Comparing to zero is not always the behavior you
want.  I seriously consider that scoped enum should
support member functions, so that you can write
a “explicit operator bool()” by yourself.


+1 for this.

enum Classes are pretty awkward to use in many contexts. I don't know if they really thought through the use cases that well.

One common way to want to use them is for a set of flags. You can write all of the boolean operators. YOu can even write a operator!() to negate it. But you can't write an operator bool(), which makes it awkward.\

At a minimum, just operator bool() for scoped enums would be great.
Reply all
Reply to author
Forward
0 new messages