简体   繁体   English

为自定义迭代器专门化 std::copy

[英]Specialize std::copy for custom iterators

From what I understand one can write template specializations for function template in the std namespace.据我所知,可以在 std 命名空间中为函数模板编写模板特化 I have written a CircularBuffer<T> class and implemented a random access iterator for this class.我编写了一个CircularBuffer<T>类并为这个类实现了一个随机访问迭代器。 As is the std::copy() algorithm works with my custom iterators but it is not optimal. std::copy()算法与我的自定义迭代器一起工作,但它不是最佳的。 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.我可以通过在内部指针上使用std::memcpy()来为简单的可复制类型编写更优化的实现。

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.我知道如何创建std::copy()的重载作为模板,输出迭代器作为模板参数。 But that cannot be done since you can only write template specializations of function templates in the std namespace.但这不能完成,因为您只能在 std 命名空间中编写函数模板的模板特化。 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.使用您的类的用户应该已经知道std::copy是什么以及它是如何工作的以及固有的性能影响。 So providing a specialization could make matters worse.因此,提供专业化可能会使事情变得更糟。 std::copy guarantees that N assignments are made; std::copy保证进行 N 次赋值; according to the standard :根据标准

Exactly (last - first) assignments完全(last - first)分配

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.此外,当使用std::copy时,它也与back_inserter或其他操纵器一起使用并不少见,这可能无法很好地进行优化。

However, you could, for instance, choose to provide a direct access to the buffer like in std::vector::data .但是,例如,您可以选择像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 https://en.cppreference.com/w/cpp/named_req/ContiguousIterator

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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