gpt4 book ai didi

C++11 为 std::chrono::time_point 添加流输出运算符

转载 作者:太空狗 更新时间:2023-10-29 20:27:19 26 4
gpt4 key购买 nike

我希望能够做到以下几点:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com