Is it possible to use boost.any as a key in a std::map(or something similiar)?

StackOverflow https://stackoverflow.com/questions/823971

  •  05-07-2019
  •  | 
  •  

Question

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

Was it helpful?

Solution

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;
}

OTHER TIPS

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.

Use if(any.type() == other.type())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top