tags:

views:

437

answers:

2

std::map<any, string> is not working so I wonder if there's another approach to have arbritary keys?

+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
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
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
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
Thanks for the example. I did have this in mind. The point is, you cannot compare across types. So, ...
dirkgently
+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 variants.

James Hopkin