c – constexpr结束istream(sentinel)迭代器有什么意义?

N2976建议在标准库中的某些位置添加constexpr.它注意到iostreams不适用于constexpr EXCEPT结束迭代器.所以istream_iterator和istreambuf_iterator被赋予了constexpr的认构造函数,就是这样.例如,您可以在 libstdc++ implementation中看到,constexpr仅在整个文件中出现一次.引发这一变化的LWG是 #1129.它说:

istream_iterator and istreambuf_iterator should support literal
sentinel values. The default constructor is frequently used to
terminate ranges,and Could easily be a literal value for
istreambuf_iterator,and istream_iterator when iterating value
types. [Rest omitted]

这对我来说并没有什么意义.有人能告诉我一个他们的意思的例子吗?

N3308是另一篇提到但并不解释问题的论文:

Some of the istream_iterator<T> constructors are required to be
constexpr if T is a literal type. The intention is to allow
existing implementation technique of storing a type of T inline to
continue to work. [libstdc++ does this,_Tp _M_value] However,it
actually rules out this technique: the default and copy constructors
of T need not be marked constexpr,and if they are not,the
istream_iterator<T> constructors Could not be instantiated as
constexpr.

以上解释了这个琐碎的拷贝构造函数和析构函数,但是并不是为什么认构造函数标记为constexpr.

此外,在线GCC 5.2.0的测试中,我复制了libstdc的实现.唯一的改变是我从istream_iterator()中删除了constexpr.在这两种情况下,组件是相同的.

With constexpr

Without constexpr

解决方法

流量迭代器的一端作为哨兵值的例子如下:
// istream_iterator example
#include <iostream>     // std::cin,std::cout
#include <iterator>     // std::istream_iterator

int main () {
  double value1,value2;
  std::cout << "Please,insert two values: ";

  std::istream_iterator<double> eos;              // end-of-stream iterator
  std::istream_iterator<double> iit (std::cin);   // stdin iterator

  if (iit!=eos) value1=*iit;

  ++iit;
  if (iit!=eos) value2=*iit;

  std::cout << value1 << "*" << value2 << "=" << (value1*value2) << '\n';

  return 0;
}

http://www.cplusplus.com/reference/iterator/istream_iterator/istream_iterator/

声明这个一个constexpr允许编译器将创建流终端迭代器的调用折叠成常量,而不是每次调用一个函数.否则可能会在循环的每次迭代中这样做.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...