Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7496823
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T18:48:24+00:00 2026-05-29T18:48:24+00:00

I’m using variant a lot in my code and I need to make comparisons

  • 0

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T18:48:24+00:00Added an answer on May 29, 2026 at 6:48 pm

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have thousands of HTML files to process using Groovy/Java and I need to
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
We're building an app, our first using Rails 3, and we're having to build

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.