std::istreambuf_iterator<char> initializes with no arguments?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 04:24:46

问题


Here is the code:

#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>

std::vector<unsigned char> bytes;
{
    std::ifstream in(name, std::ios_base::binary);
    bytes.assign(std::istreambuf_iterator<char>(in >> std::noskipws),
                 std::istreambuf_iterator<char>());
}

According to the reference, the vector.assign function takes two arguments, first and last, and takes anything in between into the vector. And the istreambuf_iterator function takes this form:

istreambuf_iterator( std::basic_istream<CharT,Traits>& is );    
istreambuf_iterator( std::basic_streambuf<CharT,Traits>* s );

These are all easy to understand, but in the snippet above, the second iterator initializer takes no arguments, what does it mean?

Also notice that the type of bytes is unsigned char, while the type of the iterator is char, isn't this a mismatch?


回答1:


the second iterator initializer takes no arguments, what does it mean?

It means it's initialized to be the end-of-stream iterator.

Also notice that the type of bytes is unsigned int, while the type of the iterator is char, isn't this a mismatch?

You mean unsigned char right? (That's what it says in your code.)

It's fine because unsigned char can be constructed from and assigned from char. Templated functions taking iterator ranges generally do not require that the types match exactly. (For the precise requirements, see Table 100 in §23.2.3 of the standard.)



来源:https://stackoverflow.com/questions/22054759/stdistreambuf-iteratorchar-initializes-with-no-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!