2011-02-06 77 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