How to compare boost::variant in order to make it a key of std::map ? Seems that operator<() is not defined for boost::variant
Asked
Active
Viewed 2,414 times
2 Answers
5
EDITED TO FIX ERROR APPLYING BOOST::APPLY_VISITOR
You can create a binary visitor for your variant, and then use boost::apply_visitor to create a comparator for your map:
class variant_less_than
: public boost::static_visitor<bool>
{
public:
template <typename T, typename U>
bool operator()( const T & lhs, const U & rhs ) const
{
// compare different types
}
template <typename T>
bool operator()( const T & lhs, const T & rhs ) const
{
// compare types that are the same
}
};
You'll probably need to overload operator()
for each possible pair of types, as apposed to using the templated operator(const T &, const U &)
. Then you'd need to declare your map like this:
class real_less_than
{
public:
template<typename T>
bool operator()(const T &lhs, const T &rhs)
{
return boost::apply_visitor(variant_less_than(), lhs, rhs);
}
};
std::map<boost::variant<T, U, V>, ValueType, real_less_than> myMap;
Edit: for what it's worth, operator<()
is defined for boost::variant
however it's defined as:
bool operator<(const variant &rhs) const
{
if(which() == rhs.which())
// compare contents
else
return which() < rhs.which();
}
which I'm assuming is not what you want.

Niki Yoshiuchi
- 16,883
- 1
- 35
- 44
-
oh, thank you. operator<() did not work for my variant as it is defined with boost::make_recursive_variant<>, not with regular boost::variant<> I will copy the code from regular boost::variant<> – user222202 Dec 03 '10 at 23:21
-
@user222202 - see my edit. You can't call boost::apply_visitor in the template list for map. You're going to need to create a function object that applies the visitor. – Niki Yoshiuchi Dec 03 '10 at 23:34
1
Perhaps you can pass a comparator to the map. Please see http://www.sgi.com/tech/stl/Map.html for an example on how to write a comparator.

kvs
- 95
- 1
- 7