Reputation: 1391
std::map<any, string>
is not working so I wonder if there's another approach to
have arbritary keys?
Upvotes: 2
Views: 2625
Reputation: 13973
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.
Upvotes: 1
Reputation: 111278
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;
}
Upvotes: 5