我希望能够做到以下几点:
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
}
哪个有效,但是从不同的命名空间调用它时我一直遇到问题。这应该只是在全局命名空间中吗?
最佳答案
当您想确保调用正确的函数时,您应该将 using
声明放在将调用它的代码范围内。
例如:
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 添加流输出运算符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16692400/