加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:19:29 所属栏目:百科 来源:网络整理
导读:N2976建议在标准库中的某些位置添加constexpr.它注意到iostreams不适用于constexpr EXCEPT结束迭代器.所以istream_iterator和istreambuf_iterator被赋予了constexpr的默认构造函数,就是这样.例如,您可以在 libstdc++ implementation中看到,constexpr仅在整个
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允许编译器将创建流终端迭代器的调用折叠成常量,而不是每次调用一个函数.否则可能会在循环的每次迭代中这样做.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读