重载std::distance等std函数是否合理?

Is it reasonable to overload std functions such as std::distance?

我有一个自定义迭代器 class 符合双向迭代器要求(但不是随机访问)。然而,两个迭代器的距离也可以在常数时间内找到。从概念上讲,it2 - it1 是有效的,但 it += n 不是(这些运算符重载都没有实际实现)。

重载 std::distance() 以允许标准库算法使用此迭代器有效地计算距离是否合理?

我发现关于篡改 std 命名空间事物的适当性的相互矛盾的信息。

关于命名空间的使用,神圣的标准是这样说的:

[namespace.std]/1(强调我的):

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

因此不允许添加重载,因为它是一个新声明。我找不到明确的禁止,因此相信在新的迭代器类型上完全特化 std::distance 函数模板应该没问题。只要您满足原始模板的要求。主要要求是 return 类型必须与 std::iterator_traits<InputIt>::difference_type 元函数指定的类型相同。它可能还需要您专精 std::iterator_traits