简体   繁体   中英

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

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?

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM