問題描述
碰到以下開頭的內容,問題的解決方式
error: invalid initialization of reference of type ‘rapidjson::Document& {aka rapidjson::GenericDocument<rapidjson::UTF8<> >&}’ from expression of type ‘rapidjson::GenericValue<rapidjson::UTF8<> >’
問題來源
我原先想進行以下的操作
// Object (python dict)
cout << "[Reading json content] document[key6] = " << endl;
cout << "[Reading json content] Get type of document[key6] = " << kTypeNames[document["key6"].GetType()] << endl; // kTypeNames[itr->value.GetType()]);
Value &value6 = document["key6"];
Document d2;
d2 = value6; // error: invalid initialization of reference of type ‘rapidjson::Document& {aka rapidjson::GenericDocument<rapidjson::UTF8<> >&}’ from expression of type ‘rapidjson::GenericValue<rapidjson::UTF8<> >’
出問題的段落在於 「d2 = value6」這個部分,
因為 value6 的格式為 Value,
而 d2 的格式為 Document,
所以當我們想進行等於的操作時,因為格式不同產生的問題。
說明
我們先解讀一下這個問題的內容敘述是什麼意思,
基本上我們可以抓到兩個關鍵字
- rapidjson::GenericDocument
- rapidjson::GenericValue
我們可以先看 rapidjson 官方的定義:
// Each JSON value is stored in a type called Value.
// A Document, representing the DOM, contains the root Value of the DOM tree.
// All public types and functions of RapidJSON are defined in the rapidjson namespace.
Document 全名為 DOM 格式 (Document Object Model, DOM),
包含著 DOM tree 裡面所有的 Value。
換句話說我們可以說,Document 可以用來作為儲存 Value 的文件格式。
我們理解上述內容後,我們就可以來看上面的 error 內容:
就是我們嘗試想把 Value 格式的內容引入至 Document,
因為格式沒有對應導致的問題。
解決方法
因為當我們想把 GenericDocument -> GenericValue 時,
可以進行以下的操作「tmpJsonObject.CopyFrom(json_content, json_content.GetAllocator()); 」。
// prepare json
Document d = make_json();
Value v(kObjectType);
v.CopyFrom(d, d.GetAllocator());