c++ - 如何将 boost::iostreams::null_sink 用作 std::ostream

标签 c++ boost

我想根据运行时给出的标志使我的输出详细/非详细。我的想法是,构建一个依赖于标志的 std::ostream,例如:

std::ostream out;
if (verbose) {
    out = std::cout
else {
    // Redirect stdout to null by using boost's null_sink.
    boost::iostreams::stream_buffer<boost::iostreams::null_sink> null_out{boost::iostreams::null_sink()};

    // Somehow construct a std::ostream from nullout
}

现在我坚持从这样一个 boost 流缓冲区构建一个 std::ostream。我该怎么做?

最佳答案

使用标准库

只需重置rdbuf:

auto old_buffer = std::cout.rdbuf(nullptr);

否则,只需使用流:

std::ostream nullout(nullptr);
std::ostream& out = verbose? std::cout : nullout;

查看 Live On Coliru

#include <iostream>

int main(int argc, char**) {
    bool verbose = argc>1;

    std::cout << "Running in verbose mode: " << std::boolalpha << verbose << "\n";

    std::ostream nullout(nullptr);
    std::ostream& out = verbose? std::cout : nullout;

    out << "Hello world\n";
}

当运行./test.exe时:

Running in verbose mode: false

当运行 ./test.exe --verbose 时:

Running in verbose mode: true
Hello world

使用 Boost Iostream

如果您坚持,您/当然可以/使用 Boost IOstreams:

Note, as per the comments, this is strictly better because the stream will not be in "error" state all the time.

Live On Coliru

#include <iostream>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/stream.hpp>

int main(int argc, char**) {
    bool verbose = argc>1;

    std::cout << "Running in verbose mode: " << std::boolalpha << verbose << "\n";

    boost::iostreams::stream<boost::iostreams::null_sink> nullout { boost::iostreams::null_sink{} };
    std::ostream& out = verbose? std::cout : nullout;

    out << "Hello world\n";
}

关于c++ - 如何将 boost::iostreams::null_sink 用作 std::ostream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33141745/

相关文章:

c++ - g++中的 undefined reference 错误

C++ 在 boost 属性树中存储浮点值

c++ - 无法在 GCC 上编译此 Boost 算法示例

c++ - 为什么在 Windows 上没有微秒分辨率的 boost::date_time?

c++ - Visual Studio 上的 boost::core::demangle typeid().name

c++ - 使用英特尔 MPI 构建 Boost.MPI

c++ - 如何在 openGL 中旋转图像?

c++ - Boost单元测试框架找不到main函数

c++ - 为什么 libstdc++ 以相反的顺序存储 std::tuple 元素?

c++ - 某些机器上 OpenGL 中的黑屏(PIXELFORMATDESCRIPTOR/SwapBuffer?)