I’m using variant a lot in my code and I need to make comparisons with the content in some places to test the content of the variant for its value.
For example:
if(equals<int>(aVariant, 0)){
//Something
} else {
//Something else
}
with this simple template function I’ve written for this purpose:
template<typename V, typename T>
inline bool equals(V& variant, T value){
return boost::get<T>(&variant) && boost::get<T>(variant) == value;
}
This works well, but the code starts to be difficult to read. I prefer to use comparison operators like that:
if(aVariant == 0){
//Something
} else {
//Something else
}
But I wasn’t able to come with a valid implementation of the operator. The problem is that the == operator has already been implemented in the variant to fails at compile-time…
Do someone know a way to implement it anyway ? Or a way to disable this limitation ? Even if I have to implement a version for each possible type contained in the variant, that’s not a problem.
Thanks
As commented, I think the cleanest way to solve this conundrum would be to enhance the implementation of
boost::variant<>with an operator policy (per operator, really) that allows clients to override behaviour for external uses. (Obviously that is a lot of generic programming work).I have implemented a workaround. This lets you implement custom operators for variants even when it has those implemented in
boost/variant.hpp.My brainwave was to use
BOOST_STRONG_TYPEDEF.The idea is to break overload resolution (or at least make our custom overloads the preferred resolution) by making our variants of a different actual type (it reminds a bit of a ‘desperate’ ADL barrier: you cannot un-
usingvisible names from a scope, and you cannot go to a ‘demilitarized namespace’ (the barrier) since the conflicting declarations reside in the class namespace itself; but you can make them not-apply to your ‘decoy’ type).Alas, that won’t work very well for
operator<and family, because boost strong-typedef actually works hard to preserve (weak) total ordering semantics with the ‘base’ type. In normal English: strong typedefs defineoperator<as well (delegating to the base type’s implementation).Not to worry, we can do a CUSTOM_STRONG_TYPEDEF and be on our merry way. Look at the test cases in main for proof of concept (output below).
Due to the interesting interactions described, I picked
operator<for this demo, but I suppose there wouldn’t be anything in your way to get a customoperator==going for your variant types.Output:
Now of course, there might be unfortunate interactions if you want to pass your custom_vt into library API’s that use TMP to act on variants. However, due to the painless conversions between the two, you should be able to ‘fight your way’ out by using detail::variant_t at the appropriate times.
This is the price you have to pay for getting syntactic convenience at the call site.