如何使用 std::copy 当类有"无符号字符和运算符[]"时

How to use std::copy when class has `unsigned char &operator[]`

本文关键字:字符 运算符 无符号 std 何使用 copy      更新时间:2023-10-16

我正在使用一个名为Buffer的类,它具有以下运算符:

unsigned char &operator[](size_t index)

我正在尝试像这样从中复制:

std::copy(buf[96], buf[96 + 32], my_uint32_t);

我认为它不起作用

/usr/include/c++/7/bits/stl_algobase.h: In instantiation of '_OI std::__copy_move_a(_II, _II, _OI) [with bool _IsMove = false; _II = unsigned char; _OI = unsigned int]':
/usr/include/c++/7/bits/stl_algobase.h:422:45:   required from '_OI std::__copy_move_a2(_II, _II, _OI) [with bool _IsMove = false; _II = unsigned char; _OI = unsigned int]'
/usr/include/c++/7/bits/stl_algobase.h:455:8:   required from '_OI std::copy(_II, _II, _OI) [with _II = unsigned char; _OI = unsigned int]'
/home/project/SimplePacketCrafter.h:36:95:   required from here
/usr/include/c++/7/bits/stl_algobase.h:377:57: error: no type named 'value_type' in 'struct std::iterator_traits<unsigned char>'
typedef typename iterator_traits<_II>::value_type _ValueTypeI;
^~~~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:378:57: error: no type named 'value_type' in 'struct std::iterator_traits<unsigned int>'
typedef typename iterator_traits<_OI>::value_type _ValueTypeO;
^~~~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:379:64: error: no type named 'iterator_category' in 'struct std::iterator_traits<unsigned char>'
typedef typename iterator_traits<_II>::iterator_category _Category;
^~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:383:9: error: no type named 'value_type' in 'struct std::iterator_traits<unsigned char>'
const bool __simple = (__is_trivial(_ValueTypeI)
~~~~~~~~~~~~~~~~~~~~~~~~~~
&& __is_pointer<_II>::__value
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
&& __is_pointer<_OI>::__value
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
&& __are_same<_ValueTypeI, _ValueTypeO>::__value);
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/7/bits/stl_algobase.h:386:44: error: no type named 'iterator_category' in 'struct std::iterator_traits<unsigned char>'
return std::__copy_move<_IsMove, __simple,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
_Category>::__copy_m(__first, __last, __result);

因为我想我应该在前两个中传递一个地址。还有

unsigned char *index(size_t index)

但它也不起作用

方法可以在这里看到

std:copy()接受迭代器,而不是引用。 这就是您收到错误的原因。

原始指针可以用作迭代器,前提是所指向的元素按顺序存储在内存中。 因此,假设缓冲区的operator[]返回对单个内存缓冲区中元素的引用,则可以使用&地址运算符获取operator[]引用的char的内存地址,然后std::copy()可以在这两个地址之间迭代:

std::copy(&buf[96], &buf[96 + 32], my_uint32_t);

或者,缓冲区的index()c_index()方法返回等效指针:

std::copy(buf.index(96), buf.index(96 + 32), my_uint32_t);
std::copy(buf.c_index(96), buf.c_index(96 + 32), my_uint32_t);