微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/c/114959.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐