mem*_*emo 5 c++ dictionary stl any poco-libraries
我有一个std :: Poco :: Any的地图,我正在尝试迭代并输出到流但我得到编译器错误.我的代码如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
该行有2个错误:
'type' cannot appear in a constant-expression
no matching function for call to 'RefAnyCast(Poco::Any&)'
Run Code Online (Sandbox Code Playgroud)
更新:
我知道模板是编译时间,而type()是运行时因此不起作用.谢谢你强调这一点.此外,DynamicAny将无法工作,因为它只接受具有DynamicAnyHolder实现的类型,并不理想.我想对这些类型强加的唯一规则是它们有<<重载.
下面是我目前正在做的,在某种程度上工作,但只转储已知类型,这不是我想要的.
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();
}
Run Code Online (Sandbox Code Playgroud)
运行时类型信息不能用于实例化模板.type_info只有在运行程序时才知道其值的实例,并不会奇怪地变成类似的类型int,std::string或者struct FooBar当编译器正在编译此代码时.
我不知道Poco库,但也许你可以使用他们的其他Any类型,DynamicAny(参见文档),希望你可以将存储的值转换std::string为输出:
os << " " << it->first << " : " << it->second.convert<std::string>() << endl;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1187 次 |
| 最近记录: |