Search code examples
c++rapidjson

What's the purpose of this function that does nearly nothing?


I'm currently reading the code of RapidJSON, and I don't understand this bit of code:

//! Reserve n characters for writing to a stream.
template<typename Stream>
inline void PutReserve(Stream& stream, size_t count) {
    (void)stream;
    (void)count;
}

//! Put N copies of a character to a stream.
template<typename Stream, typename Ch>
inline void PutN(Stream& stream, Ch c, size_t n) {
    PutReserve(stream, n);// I think this function does nothing
    for (size_t i = 0; i < n; i++)
        PutUnsafe(stream, c);
}

Can anyone explain the purpose of 'PutReserve' for me?


Solution

  • This code allows others to specialize PutReserve for their own stream types. This gives other forms of streams the option to act on the information passed here - in this case, that count characters are about to be inserted into the stream.

    You are correct that the repository has no such specialization right now, thus nothing will ever happen from this code alone. However, if this is intended as an option for extension by users (or future extension within the library), it still has a purpose. And if it remains unspecialized, the compiler will of course see that the function does nothing and completely optimize it away.


    In practice, a user that wants to use this library with his MyStream type would specialize the function like this:

    template<> void PutReserve(MyStream& stream, size_t count) {
      // ...user code
    }
    

    Note however that the C++ standard library is going to eliminate all forms of function template specialization (in namespace std) in a future C++ version, replacing them by functor classes as "customization points". See this question for the rationale.