C++ ofstream vs basic_ofstream

Viewed 894
2 Answers

There is no constructor named ofstream (constructors don't have names), and there's no class named basic_ofstream (despite of what Microsoft documentation claims).

basic_ofstream is a class template (which is different from a class), and ofstream is a typedef name a.k.a. type alias that refers to one instantiation of that template, specifically to basic_ofstream<char>.

wofstream is another such name that refers to basic_ofstream<wchar_t>.

This is the naming convention that the C++ standard library uses to define different variants of types that differ in the character type they use. Another set of names that follows this convention is basic_string, string and wstring.

This is not constructor named differently. It's a specialization. So basic_ofstream is a template. Then you have two "shortcut names":

ofstream    for basic_ofstream<char>
wofstream   for basic_ofstream<wchar_t>

Why are they named basic... maybe because standard library provides only basic versions and client can write non-basic classes and plug them in. If you look at c++ standard io library diagram, all components are prefixed as "basic".

It's usually by replacing basic_streambuf any tying custom streambuf to stream. One example taken from boost

#include <ostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>

namespace io = boost::iostreams;

int main()
{
    io::stream_buffer<io::file_sink> buf("log.txt");
    std::ostream                     out(&buf);
    // out writes to log.txt
}

It's a buffer implementation working with std::ostream.

If you want to explore fancy implementations you can checkout more from boost::iostreams library and their examples. Nice one is with gzip. It works with ifstream:

#include <fstream>
#include <iostream>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filter/gzip.hpp>

int main() 
{
    using namespace std;

    ifstream file("hello.gz", ios_base::in | ios_base::binary);
    filtering_streambuf<input> in;
    in.push(gzip_decompressor());
    in.push(file);
    boost::iostreams::copy(in, cout);
}
Related