Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

rapidjson

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?

like image 347
maidamai Avatar asked Jan 07 '19 13:01

maidamai


People also ask

What is the purpose of functions?

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.

What are some of the reason to use functions?

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.

What is a function discuss the type of function and its use?

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.


1 Answers

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.

like image 156
Max Langhof Avatar answered Nov 08 '22 16:11

Max Langhof