Unable to iterate std::map of Poco::Any
我有一个Poco :: Any的std :: map,我试图对其进行迭代并将其输出到流中,但是却遇到了编译器错误。我的代码如下:
1 2 3 4 5 6 7 8 9 | map<string, Poco::Any>::const_iterator it; map<string, Poco::Any>::const_iterator end = _map.end(); map<string, Poco::Any>::const_iterator begin = _map.begin(); for(it = begin; it != end; ++it) { const std::type_info &type = it->second.type(); // compile error here: os <<" " << it->first <<" :" << Poco::RefAnyCast<type>(it->second) << endl; } |
该行上的
2个错误:
1 2 | 'type' cannot appear in a constant-expression no matching function for call to 'RefAnyCast(Poco::Any&)' |
更新:
我知道模板是编译时的,而type()是运行时的,所以不起作用。感谢您强调这一点。同样,DynamicAny将不起作用,因为它仅接受具有DynamicAnyHolder实现的类型,而不是理想的类型。我要强加给类型的唯一规则是它们已经<<重载了。
下面是我当前正在做的事情,在一定程度上可以正常工作,但是只会转储已知类型,而这并不是我所追求的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | string toJson() const { ostringstream os; os << endl <<"{" << endl; map<string, Poco::Any>::const_iterator end = _map.end(); map<string, Poco::Any>::const_iterator begin = _map.begin(); for(map<string, Poco::Any>::const_iterator it = begin; it != end; ++it) { const std::type_info &type = it->second.type(); os <<" " << it->first <<" :"; // ugly, is there a better way? if(type == typeid(int)) os << Poco::RefAnyCast<int>(it->second); else if(type == typeid(float)) os << Poco::RefAnyCast<float>(it->second); else if(type == typeid(char)) os << Poco::RefAnyCast<char>(it->second); else if(type == typeid(string)) os << Poco::RefAnyCast<string>(it->second); else if(type == typeid(ofPoint)) os << Poco::RefAnyCast<ofPoint>(it->second); else if(type == typeid(ofVec2f)) os << Poco::RefAnyCast<ofVec2f>(it->second); else if(type == typeid(ofVec3f)) os << Poco::RefAnyCast<ofVec3f>(it->second); //else if(type == typeid(ofDictionary)) os << Poco::RefAnyCast<ofDictionary>(it->second); else os <<"unknown type"; os << endl; } os<<"}" << endl; return os.str(); } |
运行时类型信息不能用于实例化模板。
我不知道Poco库,但是也许您可以使用它们的其他任何类型,DynamicAny(请参见文档),希望可以将存储的值转换为
1 | os <<" " << it->first <<" :" << it->second.convert<std::string>() << endl; |