Markstar
Markstar

Reputation: 873

How to pass different `rapidjson::GenericObject`s to function?

I have a function where I would like to pass a rapidjson::GenericObject as a parameter, e.g.

MyObject readObject(rapidjson::GenericObject<true/false, rapidjson::Value>& obj)
{
    // ...
}

However, depending on how I extract the object, GenericObject is either const or not.

For example, it is

How can I have a function that can take both types of objects (true and false) so that I can then extract the members from it for further processing?

Upvotes: 0

Views: 455

Answers (1)

JeJo
JeJo

Reputation: 32982

How can I have a function that can take both types of objects (true and false) so that I can then extract the members from it for further processing?

You can rewrite the readObject as a template function, which will deduce the class template arguments. There you can get the non-template boolean, which can be used in if constexpr, (since ) so that only the true branch will be retained at compile time.

Something like as follows:

template<bool Flag, typename T>
auto readObject(rapidjson::GenericObject<Flag, T>& obj)
{
    // T value{..code..} ;  // if needed!

    if constexpr (Flag) {
        // code for extracting from an array....
    }
    else {
        // code for extracting from a doc....
    }
}

See a live demo in godbolt.org


Alternative to if constexpr, the solution can be SFINAEd, if you do not have C++17 compiler support.

Upvotes: 1

Related Questions