2

Apparently it is possible to have ordered maps and sets of boost::variant, like this:

typedef boost::variant<std::string, int, bool> key_type;
std::map<key_type, size_t> m;

m.insert(std::make_pair(std::string("a"), 3));
m.insert(std::make_pair(1, 7));
auto x = m.find(1);
std::cout << x->first << " " << x->second << "\n";
x = m.find(std::string("a"));
std::cout << x->first << " " << x->second << "\n";

output:

1 7
a 3

However, I find that somewhat suspicious; I looked into the source code to see how this can work, but did not get much out of it... somehow the different types have to be compared with operator<... which would need to be defined for any 2 types; apart from that comparing different types with < makes no sense in itself to me. Therefore I am wondering if there is a catch to using maps or sets of boost::variant in terms of performance. Is there a catch? Or is it ok to have maps or sets of boost::variant?

lo tolmencre
  • 3,804
  • 3
  • 30
  • 60

1 Answers1

2

I eventually found it in the documentation: http://www.boost.org/doc/libs/1_63_0/doc/html/variant/reference.html

Every type specified as a template argument to variant must at minimum fulfill the above requirements. In addition, certain features of variant are available only if its bounded types meet the requirements of these following additional concepts:

...

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

since string, int and bool are all LessThanComparable then in this case the code is safe and correct.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142