是否有 istream const 迭代器?

Is there a istream const iterator?

有std::istream常量迭代器这样的东西吗?

以下代码无法编译,因为 foo() 中的 std::istream_iterator 无法绑定到 main() 中创建的临时对象的 const std::istream 引用。

// main.cpp
#include <iostream>
#include <sstream>
#include <iterator>

void foo( const std::istream& s )
{
  std::istream_iterator<char> i( s );
  // No std::istream_const_iterator, but anything by another name?
  std::cout << *i;
}

int main( int argc, char* argv[] )
{
  std::string p( "abcdefghijklmnopqrstuvwxyz" );
  foo( std::stringstream(p) );

  return 0;
}

是否有可以绑定到 const istreamistream 迭代器?

刚问了 ,我才知道 istream_iterator ctors 初始化并 执行第一次读取 。我想我还是不清楚:读取是否一定会修改绑定 istream?如果没有,似乎应该有某种可以绑定到 const istream 的 const 迭代器,不是吗?

$ g++ --version
g++ (GCC) 9.2.1 20190827 (Red Hat 9.2.1-1)
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ g++ -g ./main.cpp && ./a.out
./main.cpp: In function ‘void foo(const istream&)’:
./main.cpp:84:34: error: binding reference of type ‘std::istream_iterator<char>::istream_type&’ {aka ‘std::basic_istream<char>&’} to ‘const istream’ {aka ‘const std::basic_istream<char>’} discards qualifiers
   84 |   std::istream_iterator<char> i( s );
      |                                  ^
In file included from /usr/include/c++/9/iterator:66,
                 from ./main.cpp:80:
/usr/include/c++/9/bits/stream_iterator.h:68:38: note:   initializing argument 1 of ‘std::istream_iterator<_Tp, _CharT, _Traits, _Dist>::istream_iterator(std::istream_iterator<_Tp, _CharT, _Traits, _Dist>::istream_type&) [with _Tp = char; _CharT = char; _Traits = std::char_traits<char>; _Dist = long int; std::istream_iterator<_Tp, _CharT, _Traits, _Dist>::istream_type = std::ba
sic_istream<char>]’
   68 |       istream_iterator(istream_type& __s)
      |                        ~~~~~~~~~~~~~~^~~

does that read necessarily modify the bound istream?

是的。

istream_iterator 是一种便利 class,它允许人们将 istream 对象视为容器,例如 std::vector 或数组。

下面,istream 是用于从流中读取的对象。是的,从流中读取确实会修改 istreamistream 还能如何跟踪内部状态以指示读取尝试是否成功、读取了多少字符等?

由于您需要读取非const istream 对象,因此能够从const istream 对象构造istream_iterator 没有任何意义。