在 main 中将 istream 定义为全局变量

Defining istream as global variable in main

我想并行读取压缩文件。我需要定义全局 istream(将其引用传递给读取函数)。这是我的代码。

#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>

std::istream &instream;

int main(int argc, char** argv) {

   std::ifstream file("test.gz", std::ios_base::in |std::ios_base::binary);
   boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
   inbuf.push(boost::iostreams::gzip_decompressor());
   inbuf.push(file);

   instream(&inbuf);
   //do something ...

   file.close();
}

我也试过这个:

std::istream tmp(&inbuf);
instream = tmp;

似乎没有任何效果。如何在 main 函数中初始化全局 istream 变量?

您可以从 std::istream 派生并附加一个缓冲区:

// Omitting boost in this example
#include <iostream>

class global_istream : public std::istream
{
    public:
    global_istream() {};
};

// No reference
global_istream instream;

int main(int argc, char** argv) {
    // Attach a buffer to the global stream.
    // Any usage of instream before the buffer has been attached is fatal. 
    instream.rdbuf(std::cin.rdbuf());
    // In your case: instream.rdbuf(&inbuf);

    //do something ...
    std::string s;
    instream >> s;
    std::cout << s << '\n';

    // Detttach the buffer from the global stream.
    // Any usage of instream after the buffer has been detached is fatal. 
    instream.rdbuf(nullptr);
}

也许更好,使用函数:

std::istream& instream()
{
    static std::ifstream file("test.gz", std::ios_base::in |std::ios_base::binary);
    static boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;

    auto setup_buffer = [] {
        inbuf.push(boost::iostreams::gzip_decompressor());
        inbuf.push(file);
        return &inbuf;
    };

    static std::istream instream(setup_buffer());
    return instream;
}