2011-02-06 72 views
5

我有一个POCO ::任何我想迭代并输出到流的std ::映射,但我得到一个编译器错误。我的代码如下:该行无法迭代POCO的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&)' 

UPDATE:

据我所知,模板是编译时间,而类型()是运行时所以不会工作。谢谢你强调这一点。 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(); 
} 

回答

7

运行时类型信息不能用于实例化模板。一个type_info的实例只有在运行该程序时才会知道它的值,当编译器编译此代码时,它不会像intstd::stringstruct FooBar那样奇迹般地变成类型。

我不知道波科库,但也许你可以使用他们的其他任何类型,DynamicAny(见documentation),这将有望让你存储的值转换为std::string输出:

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

+1 。也许应该强调的是,C++模板是编译时的事情,编译时必须知道模板参数。看到OP无法弄清楚什么是错误的,这可能是OP的消息。 – sellibitze 2011-02-06 12:03:54