c++boost-variant

boost::variant comparison not working correctly with a nan value


So I have encountered a weird problem I have a boost variant

boost::variant<double, bool, MyObject>

I doing some calculations and storing the result in the variant described above. Than I have some code where it is used like this

boost::variant<double, bool, MyObject> result_a = some_calculation(input_params_a);
boost::variant<double, bool, MyObject> result_b = some_calculation(input_params_b);
return result_a <= result_b;

The function some_calculation() when it receives -> input_params_a returns value std::numeric_limits<double>::quiet_NaN()

The function some_calculation() when it receives -> input_params_b returns constant value 2;

Now if i do this comparison operation on two doubles the result would of course be false. As comparisons with nan values results in false always. This behavior is necessary for my code.

But doing the same comparison on boost::variant results in true.

Could someone explain what is happening which is resulting in this weird behavior?

My code works fine if it the values returned are anything except nan but with nan i get this weird behavior.


Solution

  • Boost doesn't actually promise you anything about comparison operators on variant, except that they are defined when each variant branch has them. Quote from the documentation:

    LessThanComparable: variant is itself LessThanComparable if and only if every one of its bounded types meets the requirements of the concept.

    LessThanComparable in turn is defined as just having comparison operators with vague semantics. No relationship between different operators is mandated, nor any promise about keeping the semantics of operators on underlying types is made.

    This is fairly useless.

    std::variant doesn't have this problem. The semantics of operator< overloads and all the rest are defined precisely in terms of corresponding operators on underlying types.