Boost SpiritストアJSONオブジェクトを使用してJSON文字列を再帰的なデータ構造に解析しようとしています:
Value <== [null, bool, long, double, std::string, Array, Object];
Array <== [Value, Value, Value, ...];
Object <== ["name1": Value, "name2": Value, ...];
そして、ここに私のコードがあります:
#include <map>
#include <vector>
#include <string>
#include <boost/variant.hpp>
#include <boost/shared_array.hpp>
#include <boost/shared_ptr.hpp>
struct JsonNull {};
struct JsonValue;
typedef std::map<std::string, JsonValue *> JsonObject;
typedef std::vector<JsonValue *> JsonArray;
struct JsonValue : boost::variant<JsonNull, bool, long, double, std::string, JsonArray, JsonObject>
{
};
JsonValue aval = JsonObject();
コンパイルすると、次のエラーが表示されます。
Error C2440: 'initializing' : cannot convert from 'std::map<_Kty,_Ty>' to 'JsonValue'
さらに、JsonValue を JsonObject に安全にキャストする方法は? 私がやろうとすると:
boost::get<JsonObject>(aval) = JsonObject();
これにより、実行時例外/致命的なエラーが発生します。
どんな助けでも大歓迎です。
編集:
@Nicol のアドバイスに従って、次のコードを作成しました。
struct JsonNull {};
struct JsonValue;
typedef std::map<std::string, JsonValue *> JsonObject;
typedef std::vector<JsonValue *> JsonArray;
typedef boost::variant<
JsonNull, bool, long, double, std::string,
JsonObject, JsonArray,
boost::recursive_wrapper<JsonValue>
> JsonDataValue;
struct JsonValue
{
JsonDataValue data;
};
JsonObject と JsonArray を次のように簡単に操作できます。
JsonValue *pJsonVal = new JsonValue();
boost::get<JsonObject>(pCurrVal->data).insert(
std::pair<std::string, JsonValue *>("key", pJsonVal)
);
boost::get<JsonArray>(pCurrVal->data).push_back(pJsonVal);
投稿するだけで、誰もが恩恵を受けることができます。