【问题标题】:How to overload operands << to use like the ostream style [duplicate]如何重载操作数<<以像ostream样式一样使用[重复]
【发布时间】:2014-06-13 15:34:11
【问题描述】:

我正在使用线程,需要使用互斥锁保护 std::cout 操作,但我不知道如何重载运算符

myOut << "hello " << 55 << " world" << false << 45.4f << std::endl;

如果有人可以帮助我,我会感谢你。

【问题讨论】:

标签: c++ multithreading mutex ostream


【解决方案1】:

谢谢大家,但我解决了这个问题,简单但重复,我需要让操作符

    Log& operator<<(const std::string& p){
    std::lock_guard<std::mutex> locker(mutex);
    std::cout << p;
            return *this;
}

    Log& operator<<(const std::string& p){
    std::lock_guard<std::mutex> locker(mutex);
    std::cout << p.c_str();
            return *this;
}

但是需要为你想要使用的任何类型重载,他们只需为其创建一个全局变量

【讨论】:

  • 这是个好主意,我会把它添加到我的个人框架中:)
  • 您是否关注了我的链接here? 这种方法避免了operator&lt;&lt; 的任何重载,从而将您的自定义代码降至最低。更好的 imo。
  • 我现在读到,'#define log' 非常棒,而且必须更快,但是如果 std::cout 抛出异常怎么办?在这种情况下,std::lock_guard 不能用于解锁互斥锁,所以我们需要我 try-catch 来释放互斥锁并重新抛出异常。
  • @user2542813:我实际上更喜欢 Ben Voigt 接受的答案。无需涉及预处理器。
  • 嘿,如果当前操作符
猜你喜欢
  • 1970-01-01
  • 2015-10-24
  • 1970-01-01
  • 2018-06-16
  • 2011-01-09
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
相关资源
最近更新 更多