5

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();
}
4

1 に答える 1

7

ランタイム型情報を使用してテンプレートをインスタンス化することはできません。のインスタンスはtype_info、プログラムを実行したときにのみ値がわかり、魔法のように のような型にはなりませんintstd::stringまたstruct FooBar、コンパイラがこのコードをコンパイルしているときにも変わりません。

私は Poco ライブラリを知りませんが、おそらく他の Any 型である DynamicAny (ドキュメントを参照) を使用できます。これにより、保存された値をstd::string出力用に変換できることが期待されます。

os << "  " << it->first << " : " << it->second.convert<std::string>() << endl;
于 2011-02-06T11:28:28.847 に答える