c++ofstreammanipulators

Chaining C++ stream manipulators into single variable


I am chaining some stream manipulators in an ofstream like so:

std::string filename = "output.txt";
std::ofstream outputFile;
outputFile.open(filename, std::ios::trunc);
outputFile << std::setw(5) << std::scientific << std::left << variable;

Is it possible to do something like this instead?:

std::string filename = "output.txt";
std::ofstream outputFile;
outputFile.open(filename, std::ios::trunc);
std::ostream m;
m << std::setw(5) << std::scientific << std::left;   // Combine manipulators into a single variable
outputFile << m << variable;

Solution

  • A stream manipulator is just a function that a stream calls on itself through one of the operator << overloads (10-12 in the link). You just have to declare such a function (or something convertible to a suitable function pointer):

    constexpr auto m = [](std::ostream &s) -> std::ostream& {
        return s << std::setw(5) << std::scientific << std::left;
    };
    std::cout << m << 12.3 << '\n';
    

    See it live on Wandbox