简体   繁体   中英

Specialize std::copy for custom iterators

From what I understand one can write template specializations for function template in the std namespace. I have written a CircularBuffer<T> class and implemented a random access iterator for this class. As is the std::copy() algorithm works with my custom iterators but it is not optimal. It iterates through the range and copies elements one by one. I could write a more optimal implementation for trivially copiable types by using std::memcpy() on internal pointers.

My question is that even possible? I know how I would create an overload of std::copy() as a template with output iterator being the template parameter. But that cannot be done since you can only write template specializations of function templates in the std namespace. Any help in pointing me in the right direction would be helpful. From what I could gather through Google, this can't be done, but I would love to be proven wrong :)

Maybe your question should be: should I do it ?

Users who make use of your class should already be aware of what std::copy is and how it works and inherently the performance implications. So providing a specialization could make matters worse. std::copy guarantees that N assignments are made; according to the standard :

Exactly (last - first) assignments

Also, it is not uncommon that when std::copy is used, it is also used with back_inserter s or other manipulators, that will probably not play well with optimization.

However, you could, for instance, choose to provide a direct access to the buffer like in std::vector::data .

My question is that even possible?

One way around this issue that you seem to have is to export this knowledge - in a sense - to the users of your class. Just add an extra level of indirection. So instead of having iterators to the elements directly you will return iterators to the blocks of memory. Then you will be able to have Contiguous iterators.

https://en.cppreference.com/w/cpp/named_req/ContiguousIterator

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM