Why standard library does not have typed accessor for `std::istream`?

Viewed 74

When writing code involving reading from std::istream it usually disturbs me that it has to be verbose even in simple cases:

 int i = 0;
 std::cin >> i;
 // using your input here

writing a simple loop is also too verbose:

 int i = 0;
 for( std::cin >> i; i; --i ) { ... }

and it is not only verbose but forces me to extend lifetime of i where it should not be. And so on.

But with rather simple addition to standard library it can be this:

 template <class T>
 T read( std::istream &is )
 {
      auto var = T{};
      if( !is >> var ) throw std::runtime_error( "read failed" );
      return var;
 }

 template <class T>
 T read( std::istream &is, T defValue )
 {
      is >> defValue;
      return defValue;
 }

(or it could be member function of std::istream as well). So now previous cases can be as simple as:

 auto i = std::read<int>( std::cin );
 // using your input here

or the loop:

 for( auto i = std::read( std::cin, 0 ); i; --i ) { ... }

So I think it is quite obvious that it would be useful, why it is not there?

0 Answers
Related