簡體   English   中英

無法迭代Poco :: Any的std :: map

[英]Unable to iterate std::map of Poco::Any

我有一個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;
}

該行有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的一個實例,其值只在運行程序時才知道,當編譯器編譯此代碼時,它不會神奇地變成類似intstd::stringstruct FooBar的類型。

我不知道Poco庫,但也許你可以使用他們的其他Any類型,DynamicAny(參見文檔 ),希望你能將存儲的值轉換為std::string進行輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM