Often people do not recommend overloading the operator || (or &&) as you loose short circuit evaluation.
&&, ||, and , (comma) lose their special sequencing properties when
overloaded and behave like regular function calls even when they are
used without function-call notation.
Another approach would be to define a bool conversion operator, as I will show here. This requires a class MyVariant
instead of working directly with std::variant
. Therefore, this answer does not provide a solution with the exact syntax as in the question. However, I think this solution may be interesting as well.
Inspired from the (hard core) answer of @L.F. which I needed some time to understand, the below code uses a simple bool conversion operator and a Call_constructor
similar to the one of @L.F. The operators ||
, &&
, ..., can then be used.
Call_operator
struct Call_Operator
{
template <typename T>
constexpr auto operator()(T&& a) const
-> decltype(static_cast<bool>(std::declval<T>()))
{
return std::forward<T>(a);
}
bool operator()(...) const
{
throw std::exception();
}
};
MyVariant
template <typename ... Args>
struct MyVariant : public std::variant<Args...>
{
explicit operator bool()
{
return std::visit(Call_Operator{}, static_cast<std::variant<Args...>>(*this));
}
};
Usage
int main()
{
struct C {}; // operator bool not defined -> if (C{}){} does not compile
MyVariant<bool,int,char> v1 { 1 };
MyVariant<float,C> v2 { C{} };
if (v1) {} // no exception, returns true as static_cast<bool>(1) = true
if (v2) {} // throw exception since an instance of C cannot be converted to bool
if (v1 || v2) {} // no exception due to lazy evaluation (v2 is not evaluated as v1 returns true)
if (v2 || v1) {} // throws exception (C cannot be converted to bool)
if (v1 && v2) {} // throws exception ...
return 0;
}