首页 > 解决方案 > 为什么标准库没有`std::istream`的类型访问器?

问题描述

在编写涉及读取std::istream它的代码时,我通常会感到不安,即使在简单的情况下它也必须是冗长的:

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

写一个简单的循环也太冗长了:

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

它不仅冗长,而且迫使我延长 i不应该存在的生命周期。等等。

但是通过对标准库的相当简单的添加,它可以是这样的:

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

(或者它也可以是成员函数std::istream)。所以现在以前的案例可以很简单:

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

或循环:

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

所以我认为很明显它很有用,为什么它不存在?

标签: c++language-lawyerc++-standard-library

解决方案


推荐阅读