c++ 仅使用STL类型重载函数的最佳实践

lpwwtiir  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(122)

我希望重载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名称空间中?

mspsb9vt

mspsb9vt1#

你把它放在全局命名空间中,namespace std之外的任何函数,如果查找<<的名字,都会找到你的重载,并且会优先选择它而不是one defined in C++20
当然,唯一失败的地方是std::ostream_iterator,因为这是namespace std中对<<的唯一调用。
See it on coliru

相关问题