gpt4 book ai didi

c++ - 无法迭代 Poco::Any 的 std::map

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:22:13 25 4
gpt4 key购买 nike

我有一个 Poco::Any 的 std::map,我正在尝试对其进行迭代并输出到流中,但出现编译器错误。我的代码如下:

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 个错误:

'type' cannot appear in a constant-expression
no matching function for call to 'RefAnyCast(Poco::Any&)'

更新:

我知道模板是编译时的,而 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();
}

最佳答案

运行时类型信息不能用于实例化模板。 type_info 的实例其值只有在您运行程序时才知道,不会神奇地变成像 int 这样的类型, std::stringstruct FooBar当编译器正在编译这段代码时。

我不知道 Poco 库,但也许您可以使用他们的其他 Any 类型 DynamicAny(请参阅 documentation ),它有望让您将存储的值转换为 std::string用于输出:

os << "  " << it->first << " : " << it->second.convert<std::string>() << endl;

关于c++ - 无法迭代 Poco::Any 的 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4912846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com