【发布时间】:2013-05-17 13:00:48
【问题描述】:
我希望能够做到以下几点:
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
}
这行得通,但是从不同的命名空间调用它时,我总是遇到问题。这应该只在全局命名空间中是否正确?
【问题讨论】:
-
std中没有system_clock。它在std::chrono。 -
抱歉,更新了正确的修复程序。
-
请注意,您正在做一些有点不礼貌的事情,因为您正在将一个覆盖的运算符添加到您不“拥有”的两种类型。更重要的是,该标准的下一次迭代可能会编写自己的
<<重载。
标签: c++ c++11 operator-overloading ostream