[英]std::basic_ostream with parameter
I would like to know how can I insert a parameter in a std::basic_ostream I've been trying but I can't 我想知道如何在尝试过的std :: basic_ostream中插入参数,但无法
I need to insert a parameter to select which values from arista I want to print Once I have the parameter inserted the next step is easy because it is just an if condition 我需要插入一个参数,以选择要从arista中打印的值。一旦插入参数,下一步就很容易了,因为这只是一个if条件
template <typename charT>
friend std::basic_ostream<charT> &operator << (
std::basic_ostream<charT>& out, Familia &familia
) {
out << "\t Relaciones\n";
for (Vertice<cedula, relacion> &vertice : familia) {
int per = vertice.getFuente();
for (Arista<cedula, relacion> &arista : vertice) {
out << per << "->";
out << arista.getDestino() << " es" << " " << arista.getValor() << "\n";
}
}
return out;
}
There are ways in which you can add custom behavior and state to the standard stream classes via stream manipulators. 您可以通过多种方式通过流操纵器将自定义行为和状态添加到标准流类中。
But I personally feel this is too much overhead. 但是我个人觉得这是太多的开销。 What I suggest is that you define a new type that accepts the parameter and Familia
reference, and then proceeds to print: 我建议您定义一个接受参数和Familia
引用的新类型,然后继续打印:
class FormattedFamilia {
Familia const& _to_print;
int _parameter;
public:
FormattedFamilia(int parameter, Familia const& to_print)
: _parameter(parameter), _to_print(to_print)
{}
template <typename charT>
friend std::basic_ostream<charT> &operator << (
std::basic_ostream<charT>& out, FormattedFamilia const & ff
) {
if(_parameter > 0) {
// do printing using out.
}
}
};
It would have to be a friend class of Familia
, of course. 当然,它必须是Familia
的朋友班。 And using it would be as simple as this: 使用它就像这样简单:
cout << FormattedFamilia(7, familia);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.