[std :: cin在使用boost :: iostream时不可插入吗?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[std :: cin在使用boost :: iostream时不可插入吗?相关的知识,希望对你有一定的参考价值。

我认为boost :: iostreams的pipelines很方便,但似乎无法将std::cinstd::cout用作Device,例如在我的代码中:

#include <iostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filter/counter.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/copy.hpp>

namespace io = boost::iostreams;

int main()
{
    // NG: using pipelines and std::cin
    io::filtering_istream in(io::counter()|std::cin);

    // OK: not using pipelines
    //io::filtering_istream in;
    //in.push(io::counter());
    //in.push(std::cin);

    // OK: not using std::cin
    //io::filtering_istream in(io::counter()|io::file_source("/etc/hosts"));

    io::copy(in, std::cout);
    std::cout << in.component<0, io::counter>()->lines() << '
';
    std::cout << in.component<0, io::counter>()->characters() << '
';
}

只是好奇:我真的不能将std::cin与管道结合使用吗?

clang ++ 8抱怨:

In file included from prog.cc:3:
In file included from /opt/wandbox/boost-1.73.0/clang-8.0.0/include/boost/iostreams/filter/counter.hpp:19:
/opt/wandbox/boost-1.73.0/clang-8.0.0/include/boost/iostreams/pipeline.hpp:95:13: error: no matching member function for call to 'push'
        chn.push(component_);
        ~~~~^~~~
  :
/opt/wandbox/boost-1.73.0/clang-8.0.0/include/boost/iostreams/chain.hpp:484:33: note: candidate template ignored: deduced type 'basic_istream<...>' of 1st parameter does not match adjusted type 'const basic_istream<...>' of argument [with CharType = char, TraitsType = std::__1::char_traits<char>]
答案

我不知道为什么,但是只有boost::ref(std::cin)有效!

以上是关于[std :: cin在使用boost :: iostream时不可插入吗?的主要内容,如果未能解决你的问题,请参考以下文章

是否可以为 std::cin 设置超时?

std::boost::asio::post / dispatch 使用哪个 io_context?

boost::asio io_service 和 std::containers 的线程安全

std::ios::sync_with_stdio和tie()——给cin加速

使用 boost strand 和 std::mutex

std::ios::sync_with_stdio(false);