我希望重载operator<<(std::ostream&, std::chrono::duration<std::uint64, std::nano>)
--理想情况下,不需要用户到处编写using
语句。
这里的最佳实践是什么?
背景...
// Replace code like this:
using Time = std::uint64_t;
void example(Time ts) {
if (ts) { std::cout << ts; }
}
// with code like this:
using Time = std::chrono::duration<std::uint64_t, std::nano>;
void example(Time ts) {
if (!!ts) { std::cout << ts; }
}
// this 'works for me'; but it is not allowed to add overloads to `namespace std`
// The type `Time` can be used in any other namespace, and the operators are found by ADL
namespace std {
ostream& operator<<(ostream&, chrono::duration<uint64_t, nano>);
bool operator!(chrono::duration<uint64_t, nano>);
}
有没有一种方法可以在不违反namespace std
扩展规则的情况下,将重载放置在std
名称空间中?
1条答案
按热度按时间mspsb9vt1#
你把它放在全局命名空间中,
namespace std
之外的任何函数,如果查找<<
的名字,都会找到你的重载,并且会优先选择它而不是one defined in C++20。当然,唯一失败的地方是
std::ostream_iterator
,因为这是namespace std
中对<<
的唯一调用。See it on coliru