使用 boost::iostreams::tee_device?

2022-01-07 00:00:00 stream iostream c++ boost-iostreams

有人可以帮我吗?

我正在尝试执行以下操作:

I am trying to do something like the following:

#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>
#include <sstream>  
#include <cassert>  

namespace io = boost::iostreams;
typedef io::stream<io::tee_device<std::stringstream, std::stringstream> > Tee;
std::stringstream ss1, ss2;
Tee my_split(ss1, ss2); // redirects to both streams
my_split << "Testing";
assert(ss1.str() == "Testing" && ss1.str() == ss2.str());

但它不会在 VC9 中编译:

But it won't compile in VC9:

c:liboost_current_versionoostiostreamsstream.hpp(131) : error C2665: 'boost::iostreams::tee_device<Sink1,Sink2>::tee_device' : none of the 2 overloads could convert all the argument types

有人用过这个吗?我知道我可以让自己的班级来做这件事,但我想知道我做错了什么.

Has anyone gotten this to work? I know I could make my own class to do it, but I want to know what I am doing wrong.

谢谢

推荐答案

您使用 constructor-forwarding version 的 io::stream,它自己构造一个 tee-stream 并将所有参数转发给它.C++03 在将参数转发给函数时只有有限的能力(需要的重载量很容易呈指数增长).它 (io::stream) 做了以下限制:

You use the constructor-forwarding version of io::stream, which construct a tee-stream itself and forward all arguments to that. C++03 has only limited capabilities when it comes to forwarding arguments to functions (amount of overloads needed easily grow exponentially). It (io::stream) makes the following restrictions:

这些成员中的每一个都构造了一个流的实例,并将其与从给定的参数列表构造的 Device T 的一个实例相关联.所涉及的 T 构造函数必须按值或常量引用获取所有参数.

Each of these members constructs an instance of stream and associates it with an instance of the Device T constructed from the given lists of arguments. The T constructors involved must take all arguments by value or const reference.

好吧,但是 tee_device 构造函数说

Well, but the tee_device constructor says

基于给定的一对接收器构造 tee_device 的实例.如果相应的模板参数是流或流缓冲区类型,则每个函数参数都是非常量引用,否则为常量引用.

Constructs an instance of tee_device based on the given pair of Sinks. Each function parameter is a non-const reference if the corresponding template argument is a stream or stream buffer type, and a const reference otherwise.

这当然行不通.io::stream 提供了另一个以 T 作为第一个参数的构造函数.这在这里有效(至少编译.不过,断言失败.我没有使用过 boost::iostreams,所以我无能为力)

That won't work, of course. io::stream provides another constructor that takes a T as first argument. This works here (Compiles, at least. The assertion fails, though. I've not worked with boost::iostreams so i can't help with that)

namespace io = boost::iostreams;
typedef io::tee_device<std::stringstream, std::stringstream> TeeDevice;
typedef io::stream< TeeDevice > TeeStream;
std::stringstream ss1, ss2;
TeeDevice my_tee(ss1, ss2); 
TeeStream my_split(my_tee);
my_split << "Testing";
assert(ss1.str() == "Testing" && ss1.str() == ss2.str());

在调用 flush() 或流式传输 <<<;std::flush,断言通过.

After calling flush() or streaming << std::flush, the assertion passes.

相关文章