将 C++ 流操纵器链接到单个变量中

Chaining C++ stream manipulators into single variable

我正在像这样在 ofstream 中链接一些流操纵器:

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

是否可以改为执行类似的操作?:

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;

您可以编写自己的操纵器:

struct my_manipulator{};

std::ostream& operator<<(std::ostream& o, const my_manipulator& mm) {
     o << std::setw(5) << std::scientific << std::left;
     return o;
};

这将允许您编写

outputFile << my_manipulator{} << variable;

PS:Io 操纵器修改流的状态。因此它不能完全按照您要求的方式工作。您正在修改 m 的状态。将状态从一个流转移到另一个流是可能的,但恕我直言,比必要的更复杂。

PPS:请注意,我定义自定义 io-manipulator 的方式还可以,但要查看更符合流操纵器精神的实现,请参阅 (通常io-manipulators 是函数,我使用了一个需要更多样板的标签。

流操纵器只是流通过 operator << 重载之一(link 中的 10-12)调用自身的函数。您只需要声明这样一个函数(或可转换为合适的函数指针的东西):

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