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

前端之家收集整理的这篇文章主要介绍了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&C++相关文章