f_3464gh
f_3464gh

Reputation: 160

C++ and RapidJson: Define Value without document

I'm using RapidJson to parse Json-Files in my C++ application.

Inside my json file there is an array of float values: threshs = [0.2, 0.3]. This array is stored as an attribute of a Settings class. The type is const Value*. If I need to access the data I can call (*settings->threshs)[i].GetFloat().

If there is an error while parsing, I want to use default values that are set in Settings.h. This smoothly works for Floats, Integers, bools.... Problem is: How can I manually create a const Value* without creating a document. So in my header file I want s.th. like:

const Value* = {0.2, 0.3};

Is this possible? The only solution I had was to change the type of thresh to a vector and at the parsing to loop over the json array and copy the values into the vector

Upvotes: 0

Views: 1635

Answers (1)

m88
m88

Reputation: 1988

This code compiles/runs without issue on my setup:

#include <iostream>

#include <rapidjson/allocators.h>
#include <rapidjson/document.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/rapidjson.h>

int main()
{
    using namespace std;
    using namespace rapidjson;

    Value val(kArrayType);

    //{
    MemoryPoolAllocator alloc;
    val.PushBack(Value(0.1).Move(), alloc);
    val.PushBack(Value(0.2).Move(), alloc);
    //}

    Document doc;
    doc.SetObject().AddMember("arr", val, doc.GetAllocator());

    StringBuffer sb;
    PrettyWriter<StringBuffer> writer(sb);
    doc.Accept(writer);
    cout << sb.GetString() << endl;

    return 0;
}

Output:

{
    "arr": [
        0.1,
        0.2
    ]
}

Btw if you uncomment the { and } the allocator will be destroyed before you can add the Value and this is what you'll get:

{
    "arr": [
        null,
        null
    ]
}

On the plus side, it doesn't crash.

Upvotes: 1

Related Questions