0

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?

JeJo
  • 30,635
  • 6
  • 49
  • 88
Markstar
  • 639
  • 9
  • 24

1 Answers1

1

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88
  • Thank you very much for your detailed reply and the links! Since the code is the same for both `Flag == true` and `Flag == false` and `T` is always `rapidjson::Value`, it works with `template auto readObject(rapidjson::GenericObject& obj)`. However, there is one thing that is left: While having everything in the header file works, I had the function declaration in the header file while the definition was in a cpp file. Now I can't get it to work. Looking [here](https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl), it does seem a bit complicated. – Markstar Mar 14 '23 at 08:17
  • Yeah, I linked the same site in my reply, that's where I got the solution to simply move the definition to the header file from. I was hoping to get this part to work: "*The other solution is to leave the definition of the template function in the .cpp file and simply add the line template void foo(); to that file:*", but I don't get it right in this case. – Markstar Mar 14 '23 at 09:12