c++ - 为什么标准库没有`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 ) { ... }
所以我认为很明显它很有用,为什么它不存在?
解决方案
推荐阅读
- javascript - 如何在打字稿中从函数访问数据到父级
- javascript - 从嵌套的 firebase 对象存储数据
- imagemagick - 在 OS X El Capitan 中使用自制软件安装 Imagemagick 时出错
- elasticsearch - 在 RapidMiner 中使用弹性搜索
- winapi - Win32Api 窗口移动
- github - 图片未嵌入到 GitHub 的 md 文件中
- python - 在我自己实现的 kNN 算法中找到训练和测试错误
- python - 仅为一个应用程序修改标准类
- r - 无法配置 R 语言“需要 bzip2 库和标头”
- apache-spark - 如何将 Spark DataFrame 插入 Hive 内部表而不重复?