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?
Functions are "self contained" modules of code that accomplish a specific task. Functions usually "take in" data, process it, and "return" a result. Once a function is written, it can be used over and over and over again.
Functions provide a couple of benefits: Functions allow the same piece of code to run multiple times. Functions break long programs up into smaller components. Functions can be shared and used by other programmers.
A function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output. Let A & B be any two non-empty sets; mapping from A to B will be a function only when every element in set A has one end, only one image in set B.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With