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

283 Views Asked by At

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

  • When extracting from an array
    rapidjson::GenericObject<true, rapidjson::Value> // true
    
  • When extracting from a doc
    rapidjson::GenericObject<false, rapidjson::Value>  // false
    

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?

1

There are 1 best solutions below

2
JeJo On BEST ANSWER

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.