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

早过忘川 提交于 2019-12-24 15:47:55

问题


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).

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

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


回答1:


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

[namespace.std]/1 (emphasis mine):

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.

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.



来源:https://stackoverflow.com/questions/47029990/is-it-reasonable-to-overload-std-functions-such-as-stddistance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!