这个几乎什么都不做的函数的目的是什么?

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

我正在阅读RapidJSON的代码,我不明白这段代码:

//! 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);
}

任何人都可以为我解释 'PutReserve' 的目的吗?

此代码允许其他人针对他们自己的流类型专门化 PutReserve。这为其他形式的流提供了对此处传递的信息进行操作的选项 - 在这种情况下,count 个字符将被插入到流中。

你是对的,存储库目前没有这样的专业化,因此仅此代码不会发生任何事情。然而,如果这是作为用户扩展的一个选项(或未来在库中扩展),它仍然有一个目的。如果它仍然是非特化的,编译器当然会看到该函数什么都不做,并将其完全优化掉。


实际上,想要将此库与他的 MyStream 类型一起使用的用户会像这样专门化函数:

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

但是请注意,C++ 标准库将在未来的 C++ 版本中消除所有形式的函数模板特化(在 namespace std 中),将它们替换为仿函数 类 作为 "customization points".参见 了解基本原理。