首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带参数的std::basic_ostream

带参数的std::basic_ostream
EN

Stack Overflow用户
提问于 2017-08-08 15:26:30
回答 1查看 135关注 0票数 0

我想知道如何在std::basic_ostream中插入参数我一直在尝试但不能

我需要插入一个参数来选择要从arista打印哪些值。插入参数后,下一步很容易,因为它只是一个if条件

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

发布于 2017-08-08 15:35:31

有一些方法可以通过流操纵器向标准流类添加自定义行为和状态。

但是我个人觉得这个开销太大了。我建议您定义一个接受参数和Familia引用的新类型,然后继续打印:

代码语言:javascript
复制
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.
     }
  }
};

当然,它必须是Familia的一个friend类。使用它就像这样简单:

代码语言:javascript
复制
cout << FormattedFamilia(7, familia);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45561857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档