4

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

Baptiste Wicht
  • 7,472
  • 7
  • 45
  • 110
  • @R.MartinhoFernandes I don't think he will get the syntax he wants with this though. – pmr Feb 05 '12 at 21:50
  • Oh, I didn't know this scenario was explicitly forbidden by the variant developers. Anyone knows what's the rationale? – R. Martinho Fernandes Feb 05 '12 at 22:07
  • 1
    @R.MartinhoFernandes: no one thought of it? They could have used `traits` or comparison `policies`. @Baptiste, you could amend the variant class to do that and submit the idea to the boost list – sehe Feb 05 '12 at 22:16
  • 1
    The manual says: "The overload returning void exists only to prohibit implicit conversion of the operator's right-hand side to variant; thus, its use will (purposefully) result in a compile-time error." - You can do `if (aVariant == variant_type(0))`, but I don't see what would be wrong with a user-defined function (where the argument types can normally be deduced). – UncleBens Feb 05 '12 at 22:19
  • @UncleBens There is nothing wrong with my user-defined function, only the syntax that is a bit heavy in my code. – Baptiste Wicht Feb 06 '12 at 10:16

1 Answers1

8

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-using visible 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 define operator< 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 custom operator== going for your variant types.

#include <boost/variant.hpp>
#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>

/////////////////////////////////////////////////////
// copied and reduced from boost/strong_typedef.hpp
#define CUSTOM_STRONG_TYPEDEF(T, D)                                 \
struct D                                                            \
    /*: boost::totally_ordered1< D           */                     \
    /*, boost::totally_ordered2< D, T        */                     \
    /*> >                                    */                     \
{                                                                   \
    T t;                                                            \
    explicit D(const T t_) : t(t_) {};                              \
    D(){};                                                          \
    D(const D & t_) : t(t_.t){}                                     \
    D & operator=(const D & rhs) { t = rhs.t; return *this;}        \
    D & operator=(const T & rhs) { t = rhs; return *this;}          \
    operator const T & () const {return t; }                        \
    operator T & () { return t; }                                   \
    /*bool operator==(const D & rhs) const { return t == rhs.t; } */\
    /*bool operator<(const D & rhs) const { return t < rhs.t; }   */\
};

namespace detail
{
    typedef boost::variant<unsigned int, std::string> variant_t;

    struct less_visitor : boost::static_visitor<bool>
    {
        bool operator()(const std::string& a, int b) const
        { return boost::lexical_cast<int>(a) < b; }

        bool operator()(int a, const std::string& b) const
        { return a < boost::lexical_cast<int>(b); }

        template <typename T>
            bool operator()(const T& a, const T& b) const
            { return a < b; }
    };

    struct variant_less
    {
        less_visitor _helper;

        bool operator()(const variant_t& a, const variant_t& b) const
        { return boost::apply_visitor(_helper, a, b); }
    };
}

CUSTOM_STRONG_TYPEDEF(detail::variant_t, custom_vt);

namespace 
{
    bool operator<(const custom_vt& a, const custom_vt& b)
        { return detail::variant_less()(a, b); }

    std::ostream& operator<<(std::ostream& os, const custom_vt& v)
        { return os << (const detail::variant_t&)v; }
}

int main()
{
    const detail::variant_t I(43), S("42");
    const custom_vt i(I), s(S);

    // regression test (compare to boost behaviour)
    std::cout << "boost:   " << I << " < " << S << ": " << std::boolalpha << (I<S) << "\n";
    std::cout << "boost:   " << S << " < " << I << ": " << std::boolalpha << (S<I) << "\n";

    // FIX1: clumsy syntax (works for boost native variants)
    detail::variant_less pred;
    std::cout << "clumsy:  " << i << " < " << s << ": " << std::boolalpha << pred(i,s) << "\n";
    std::cout << "clumsy:  " << s << " < " << i << ": " << std::boolalpha << pred(s,i) << "\n";

    std::cout << "clumsy:  " << I << " < " << S << ": " << std::boolalpha << pred(I,S) << "\n";
    std::cout << "clumsy:  " << S << " < " << I << ": " << std::boolalpha << pred(S,I) << "\n";

    // FIX2: neat syntax (requires a custom type wrapper)
    std::cout << "custom:  " << i << " < " << s << ": " << std::boolalpha << (i<s) << "\n";
    std::cout << "custom:  " << s << " < " << i << ": " << std::boolalpha << (s<i) << "\n";

}

Output:

boost:   43 < 42: true
boost:   42 < 43: false
clumsy:  43 < 42: false
clumsy:  42 < 43: true
clumsy:  43 < 42: false
clumsy:  42 < 43: true
custom:  43 < 42: false
custom:  42 < 43: true

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.

sehe
  • 374,641
  • 47
  • 450
  • 633