std::map<any, string>
is not working so I wonder if there's another approach to
have arbritary keys?
views:
437answers:
2
+4
A:
I think the issue is not with Boost::Any
, but rather with the fact that you are not specifying a custom comparator. Since map
is a sorted associative container, you need to have a comparator.
The following works for me: tailor it according to your purposes:
#include <iostream>
#include <map>
#include <boost/any.hpp>
using namespace std;
struct cmp {
bool operator()(const boost::any& l, const boost::any& r) {
try
{
int left = boost::any_cast<int>(l);
int right = boost::any_cast<int>(r);
return left < right;
}
catch(const boost::bad_any_cast &)
{
return false;
}
return false;
}
};
int main() {
map<boost::any, string, cmp> ma;
boost::any to_append = 42;
ma.insert(std::make_pair(to_append, "int"));
if (ma.find(42) != ma.end()) {
cout << "hurray!\n";
}
return 0;
}
dirkgently
2009-05-05 09:11:40
Your comparison functor isn't valid for use in a map because it can return false for both a < b and b < a for some (a, b) pairs.
James Hopkin
2009-05-05 09:33:50
An example would be nice. Anyway, I do think more such cases can be constructed where the comparator will fail. The very idea of having an ordering across types doesn't sound good to me.
dirkgently
2009-05-05 09:38:48
An example would be any any pair where one (a) contains and int and the other (b) contains a string. Your comparator would return false for a<b and b<a.I guess you could fix this by converting both any objects to a string (id they're streamable), but then you might as well use string as a key...
jon hanson
2009-05-05 09:49:54
Thanks for the example. I did have this in mind. The point is, you cannot compare across types. So, ...
dirkgently
2009-05-05 10:21:35
+1
A:
You might want to look at boost::variant
rather than boost::any
, so you can be sure all the types you are using are comparable.
Using visitors would be the best way to provide a comparison operator for variant
s.
James Hopkin
2009-05-05 09:43:06