私は、Pocoのマップ::マップを持っていますが、私は "ストリームを反復して出力しようとしていますが、コンパイラのエラーが出ます。私のコードは以下の通りです:
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&)"
更新:
私はテンプレートがコンパイル時であることを理解しています一方、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();
}
回答:
回答№1の場合は7実行時の型情報を使用してテンプレートをインスタンス化することはできません。のインスタンス type_info
その値はあなたがプログラムを実行するときにのみ知られていますが、魔法のようなタイプに変わっていません int
, std::string
または struct FooBar
コンパイラがこのコードをコンパイルしているときです。
私はPocoライブラリを知っているわけではありませんが、おそらくあなたは他のAnyタイプのDynamicAnyを使うことができます(see ドキュメンテーション)これは、保存された値を std::string
出力のために:
os << " " << it->first << " : " << it->second.convert<std::string>() << endl;