重载std函数如std :: distance是否合理? [英] Is it reasonable to overload std functions such as std::distance?

查看:237
本文介绍了重载std函数如std :: distance是否合理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a custom iterator class conforming to the bidirectional iterator requirements (but not random access). However, the distance of two iterators can also be found in constant time. Conceptually, it2 - it1 is efficient, but it += n is not (neither of these operator overloads is actually implemented).

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

Is it reasonable to overload std::distance() to allow standard library algorithms to compute distances efficiently with this iterator?

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

I found conflicting information about the appropriateness of tampering with std namespace things.

推荐答案

关于名称空间使用,神圣标准说:

With regard to namespace use, the holy standard says this:

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


如果将C ++程序的声明或
定义添加到命名空间std或命名空间中,则C ++程序的行为是未定义的。除非另有说明,否则命名空间std
如果声明取决于用户定义的类型且
专门化符合标准库要求,则程序可以将任何标准库模板的模板
特化添加到命名空间std仅

原始模板并未明确禁止

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

So adding an overload is disallowed, since it's a new declaration. I couldn't find an explicit prohibition, and therefore believe that fully specializing the std::distance function template on your new iterator type should be fine. So long as you fulfill the requirements of the original template. The main requirement being that the return type must be the same as specified by the std::iterator_traits<InputIt>::difference_type meta-function. It may require you to specialize std::iterator_traits as well.

这篇关于重载std函数如std :: distance是否合理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆