How to use comparison operators on variant with contained types?

后端 未结 1 1709
梦毁少年i
梦毁少年i 2021-02-10 19:42

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:

<
相关标签:
1条回答
  • 2021-02-10 20:10

    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.

    0 讨论(0)
提交回复
热议问题