【发布时间】:2015-01-12 21:55:13
【问题描述】:
前几天我试过gcc-4.9.1:
int main()
{
int a[10][20][30];
int b[10][20][30];
::std::copy(::std::begin(a), ::std::end(a), ::std::begin(b));
return 0;
}
当然,它产生了一个错误:
In file included from /usr/include/c++/4.9.2/bits/char_traits.h:39:0,
from /usr/include/c++/4.9.2/ios:40,
from /usr/include/c++/4.9.2/ostream:38,
from /usr/include/c++/4.9.2/iostream:39,
from t.cpp:1:
/usr/include/c++/4.9.2/bits/stl_algobase.h: In instantiation of 'static _Tp* std::__copy_move<_IsMove, true, std::random_access_iterator_tag>::__copy_m(const _Tp*, const _Tp*, _Tp*) [with _Tp = int [20][30]; bool _IsMove = false]':
/usr/include/c++/4.9.2/bits/stl_algobase.h:396:70: required from '_OI std::__copy_move_a(_II, _II, _OI) [with bool _IsMove = false; _II = int (*)[20][30]; _OI = int (*)[20][30]]'
/usr/include/c++/4.9.2/bits/stl_algobase.h:434:38: required from '_OI std::__copy_move_a2(_II, _II, _OI) [with bool _IsMove = false; _II = int (*)[20][30]; _OI = int (*)[20][30]]'
/usr/include/c++/4.9.2/bits/stl_algobase.h:466:17: required from '_OI std::copy(_II, _II, _OI) [with _II = int (*)[20][30]; _OI = int (*)[20][30]]'
t.cpp:10:62: required from here
/usr/include/c++/4.9.2/bits/stl_algobase.h:373:4: error: static assertion failed: type is not assignable
static_assert( is_copy_assignable<_Tp>::value,
^
我认为这对于std::copy() 来说不是什么大问题,就像处理多维数组的std::begin() 和std::end() 一样。这是当前 C++ 标准的遗漏吗?如何解决?
编辑:我相信,标准可以解决这个问题:
namespace std
{
template <typename T, size_t M, size_t N>
constexpr typename remove_all_extents<T>::type*
begin(T (&array)[M][N])
{
return begin(array[0]);
}
template <typename T, size_t M, size_t N>
constexpr typename remove_all_extents<T>::type*
end(T (&array)[M][N])
{
return end(array[M - 1]);
}
}
【问题讨论】:
-
这是一个遗漏(但我猜,很大程度上是故意的)。通过不使用数组的数组来解决它。
-
使用
std::array代替普通数组可以解决问题。 -
@Zyx2000 为什么一直忽略多维数组?是的,
std::array也有帮助,但数组类型是 C++ 的一部分,就像std::array。
标签: c++ arrays c++11 multidimensional-array