Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::wostream_iterator

Why there are no std::wostream_iterator in C++?

Is there any good reason for this?

#include <fstream>
#include <iterator>
#include <string>
#include <vector>

int main()
{
    std::vector<std::wstring> myvec = { L"first", L"second" };

    std::wofstream f("New.txt");
//  std::copy(myvec.begin(), myvec.end(), std::wostream_iterator<std::wstring>(f)); // Error
//  std::copy(myvec.begin(), myvec.end(), std::ostream_iterator<std::wstring>(f)); // Error
    std::copy(myvec.begin(), myvec.end(), std::ostream_iterator<std::wstring, wchar_t>(f)); // Ok
    std::copy(myvec.begin(), myvec.end(), std::ostream_iterator<std::wstring, wchar_t, std::char_traits<wchar_t>>(f)); // Ok
}
like image 800
FrozenHeart Avatar asked Oct 07 '22 20:10

FrozenHeart


1 Answers

Because std::ostream_iterator is not typedef (and std::wstring is typedef on std::basic_string with charT = wchar_t).

template <class T, class charT = char, class traits = char_traits<charT> >
class ostream_iterator:
public iterator<output_iterator_tag, void, void, void, void>

Second copy operation

std::copy(myvec.begin(), myvec.end(), std::ostream_iterator<std::wstring>(f));

is incorrect, since

typedef basic_ostream<charT,traits> ostream_type;

so, in this case ostream_type is basic_ostream<char, std::char_traits<char> >

ostream_iterator(ostream_type& s);

Constructor can receive only this type, but we pass basic_ofstream<wchar_t, std::char_traits<wchar_t> >, it's incorrect.

like image 83
ForEveR Avatar answered Oct 10 '22 03:10

ForEveR