C++如何同时进行定制和编写

C++ how to cout and write at the same time

本文关键字:何同时 C++      更新时间:2023-10-16

在阅读了以下内容后:C++用简单的代码同时写入文件和控制台输出,我正试图编写一个函数来处理for循环中的内容。但我不知道如何将这样一段代码:setw(3) << right << get<0>(*it_party) << setw(9) << ""作为一个参数传递到一个函数中,以便cout和file都可以使用它

The helper function I am trying to write:
void print(std::ostream &os1, std::ostream &os2, const [I don't know what to put in here])
{
os1 << the argument; // cout
os2 << the argument; // file
}
ofstream file;
file.open("test.txt");
for (auto it_party = parties_.begin(); it_party != parties_.end(); ++it_party) {
cout << setw(3) << right << get<0>(*it_party) << setw(9) << "";
file << setw(3) << right << get<0>(*it_party) << setw(9) << "";
cout << setw(7) << left << get<1>(*it_party) << setw(1) << "";
file << setw(7) << left << get<1>(*it_party) << setw(1) << "";
...
...
}

如果你想像那样把输出串在一起,你可能会发现使用某种"tee"类更容易:

class Tee {
private:
std::ostream &os1, &os2;
public:
Tee(std::ostream &os1, std::ostream &os2) : os1(os1), os2(os2) { }
template <typename T>
Tee& operator<<(const T &thing) {
os1 << thing;
os2 << thing;
return *this;
}
};

这需要一个模板参数,所以它不在乎您是传递right还是传递setw(3)。你可以像这样使用它:

Tee t(std::cout, std::cout);
t << setw(10) << "right" << " Thing" << setw(9);

使用std::stringstream可以轻松完成此操作。我不知道get<>()是什么,但这里有一个基本的例子:

#include <string>  
#include <iostream> 
#include <sstream>   
#include <fstream>
void fn(std::string output) {
std::ofstream file("file.txt");
std::cout << output;
file << output;
}
int main() {
std::stringstream buffer;
buffer << "some random text" << std::endl;
fn(buffer.str());
return 0;
}

不幸的是,您不能将所有这些内容仅作为一个参数传递。但也有一些先进的技术可以帮助你,比如可变模板和C++17倍表达式。

可变模板是一种功能,例如,它允许您在编译时传递未知数量的不同类型的参数。您可以在标准库中看到一些这样的例子,例如std::tuple。

折叠表达式是与前一个组合使用的另一个功能。它允许您编写非常简单的可变模板代码:

template<typename ...Args>
void printer(const Args &... args) {
(std::cout << ... << args) << 'n';
}

在这里,我们看到了一个函数,它将一些const &带到一些参数(我们不知道它们的计数或不同类型(,但我们有一些奇特的东西,比如args,一个参数包,它表示我们的参数,Args作为它们的类型"打包"在一起;

您可以使用它将任意参数传递到流:

template<typename ...Args>
void printer(const Args &... args) {
(std::cout << ... << args);
(file << ... << args);
}

在这个解决方案中还有其他一些需要改进的地方,比如完美的转发,但这些还有待进一步研究。