Debugging ofstream.(C++)

Debugging ofstream.(C++)

本文关键字:C++ ofstream Debugging      更新时间:2023-10-16

我需要创建一个流调试,它具有如下功能:

#define DEBUG true
int main() {
    debug << "Hello Worldn";
}

上述情况下的输出应为:Hello World

对于以下代码-

#define DEBUG false
int main() {
    debug << "Hello Worldn";
}

输出应为。任何建议我应该如何进行。

根据您的使用,我认为debug需要宏,因为没有其他方法可以获取DEBUG的值。一个简单的定义是这样的:

#define debug (debugstream << enable<DEBUG>)
extern std::ostream debugstream;
template <bool Enable>
std::ostream& enable(std::ostream& out) {
    if (Enable) {
        out.clear();
    }
    else {
        out.setstate(std::ios_base::badbit);
    }
    return out;
}
std::ostream debugstream(std::cout.rdbuf()); // probably defined in a separate translation unit

这里的诀窍是使用流的启动启用/禁用输出的打印:当流处于良好状态时,即如果设置了std::ios_base::failbitstd::ios_base::badbit,则不会生成任何输出(由正确写入的输出运算符(。可以通过设置/取消设置流缓冲区来强制使用此行为,而不是使用 rdbuf()

正如我从您的问题中了解到的那样,您希望有一个单独的调试流(与 std::coutstd:cerr 相反(。你可以通过制作一个"空流"来实现这一点,它只是吃掉所有东西而不做任何事情。

如果你的编译器足够聪明,那么它甚至应该最终删除大部分内容。

class NullStream {};
template<typename T>
NullStream& operator<<(NullStream& s, T const &) { return s; }
NullStream& operator<<(NullStream& s, std::ostream&(std::ostream&)) { return s; }

现在,根据您的宏,您可以决定是使用NullStream还是实际ostringstream

#if DEBUG
std::ostringstream debug;
#else
NullStream debug;
#endif

像这样测试它:

debug << "Hello Worldn";
debug << 12345 << "n";
debug << "Test" << std::endl;
#if DEBUG
std::cout << "Debug:" << std::endl;
std::cout << debug.str() << std::endl;
#endif

如果不0 DEBUG,则会产生:

调试:

世界您好

12345

测试

请注意,NullStream本身没有任何std::ostream的功能,因此另一种解决方案可能是从std::ostream派生并丢弃它收到的任何输入。