> On 29 Oct 2016, at 23:51, Andrzej Krzemieński <
akrz...@gmail.com> wrote:
>
> I do not know of any practical use of explicit conversion operators except for the contextual conversion to bool. And it is only this conversion that I am interested in.
If all you need is boolean conversion, how about
template<typename E>
constexpr std::enable_if_t<std::is_enum_v<E>,bool> is(E e) noexcept
{
return e == E(true);
}
to be used like
if(is(skipUnused)) { ... }
Instead of is(), you could also use operators, e.g.
+skipUnused
or
!skipUnused
(the latter might actually be sensible, but inconsistent if skipUnused itself is not convertible to bool)
There is a caveat with using boolean enums, i.e., if the user writes:
enum class SkipUnused { Yes, No };
(Note the order of the values).
There is no way for us to detect this, unless we explicitly would expect a value called Yes (or should it be YES or TRUE?) and change the above to
template<typename E>
constexpr std::enable_if_t<std::is_enum_v<E>,bool> is(E e) noexcept
{
return e == E::Yes;
}
> Do you think, it would be acceptable to add such explicit conversion to the underlying type, for enum classes?
If anything, it should be explicit for a type, not implicit for all enums. Maybe allowing something like:
enum class SkipUnused { No, Yes };
explicit constexpr SkipUnused::operator bool() = default;
or
explicit constexpr SkipUnused::operator bool() noexcept { return *this == Yes; }
where *this refers to the enum value and Yes is in the scope of SkipUnused, hence no SkipUnused::Yes is needed. Something like a "member" of an enum class. This might also allow other conversions (explicitly), making a possible proposal usable in more contexts. I'm not really sure it is worth it, though.