【问题标题】:boost::iostreams::counter doesn't seem to workboost::iostreams::counter 似乎不起作用
【发布时间】:2012-11-11 13:48:24
【问题描述】:

我正在玩 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”不同的地址。我想这是管道中的某种复制?如果是这样,过滤“计数器”有什么用?

【问题讨论】:

    标签: c++ boost iostream


    【解决方案1】:

    查看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;
    }
    

    【讨论】:

    • 如果你想直接在管道中使用boost::ref(避免使用out.push...,你需要使用这个post in the mailing list中的宏。只需将BOOST_IOSTREAMS_EXTENDED_PIPABLE(io::basic_counter,1)放在main之外。跨度>
    猜你喜欢
    • 1970-01-01
    • 2013-01-30
    • 2016-11-29
    • 2016-02-01
    • 2020-09-23
    • 2010-12-05
    • 2011-06-14
    • 2015-01-10
    • 2016-02-24
    相关资源
    最近更新 更多