C ++ 11为std :: chrono :: time_point添加流输出运算符 [英] C++11 Adding a stream output operator for std::chrono::time_point

查看:117
本文介绍了C ++ 11为std :: chrono :: time_point添加流输出运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够执行以下操作:

I would like to be able to do the following:

std::cerr << std::chrono::system_clock::now() << std::endl;

并获得以下信息:

Wed May  1 11:11:12 2013

所以我写了以下内容:

template<typename Clock, typename Duration>
std::ostream &operator<<(std::ostream &stream,
  const std::chrono::time_point<Clock, Duration> &time_point) {
  const time_t time = Clock::to_time_t(time_point);
#if __GNUC__ > 4 || \
    ((__GNUC__ == 4) && __GNUC_MINOR__ > 8 && __GNUC_REVISION__ > 1)
  // Maybe the put_time will be implemented later?
  struct tm tm;
  localtime_r(&time, &tm);
  return stream << std::put_time(tm, "%c");
#else
  char buffer[26];
  ctime_r(&time, buffer);
  buffer[24] = '\0';  // Removes the newline that is added
  return stream << buffer;
#endif
}

这是可行的,但是从不同的命名空间调用此方法时,我总是遇到问题.应该只在全局名称空间中使用是正确的吗?

Which works, but I keep getting issues when calling this from different namespaces. Is it correct that this should just be in the global namespace?

推荐答案

当您要确保调用了正确的函数时,应在要调用它的代码范围内放置一个using声明.

When you want to be sure that the right function gets called, you should put put a using declaration in the scope of the code that will call it.

例如:

namespace pretty_time {
  /* your operator<< lives here */
}


void do_stuff() {
  using namespace pretty_time;   // One way to go is this line
  using pretty_time::operator<<; // alternative that is more specific (just use one of these two lines, but not both)
  std::cout << std::chrono::system_clock::now();
}

这篇关于C ++ 11为std :: chrono :: time_point添加流输出运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆