简体   繁体   English

是否可以将boost.any用作std :: map(或类似名称)中的键?

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

std::map<any, string>无法正常工作,所以我想知道是否还有另一种方法来使用密钥?

I think the issue is not with Boost::Any , but rather with the fact that you are not specifying a custom comparator. 我认为问题不在于Boost::Any ,而在于您未指定自定义比较器。 Since map is a sorted associative container, you need to have a comparator. 由于map是一个排序的关联容器,因此需要一个比较器。

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

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. 您可能需要查看boost::variant而不是boost::any ,因此可以确保所使用的所有类型都是可比较的。

Using visitors would be the best way to provide a comparison operator for variant s. 利用游客将提供一个比较操作的最佳方式variant秒。

使用if(any.type()== other.type())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM