我在玩 boost::iostreams 并且用户指南讨论了过滤器“计数器”。所以我用这段代码试试:
#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/filter/counter.hpp>
namespace io = boost::iostreams;
int main()
{
io::counter cnt;
io::filtering_ostream out(cnt | io::null_sink());
out << "hello";
std::cout << cnt.lines() << " " << cnt.characters() << std::endl;
}
它总是给
0 0
这似乎不是我所期待的。 使用 gdb 的初步跟踪表明正在进行计数的计数器对象具有与对象“cnt”不同的地址。我想这是管道中的某种复制?既然如此,过滤“计数器”还有什么用?
最佳答案
查看the documentation您可以使用:
#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/filter/counter.hpp>
namespace io = boost::iostreams;
int main()
{
io::counter cnt;
io::filtering_ostream out(cnt | io::null_sink());
out << "hello";
std::cout << out.component<io::counter>(0)->lines() << " " << out.component<io::counter>(0)->characters() << std::endl;
}
或:
#include <iostream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/null.hpp>
#include <boost/iostreams/filter/counter.hpp>
#include <boost/ref.hpp>
namespace io = boost::iostreams;
int main()
{
io::counter cnt;
io::filtering_ostream out;
out.push(boost::ref(cnt));
out.push(io::null_sink());
out << "hello";
std::cout << cnt.lines() << " " << cnt.characters() << std::endl;
}
关于c++ - boost::iostreams::counter 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13524960/