使用 C 数组,编写采用任意大小数组的代码相当容易:
void func( T* itBegin, T* itEnd );
void main() {
T arr1[1];
func( std::begin(arr1), std::end(arr1) );
T arr2[2];
func( std::begin(arr2), std::end(arr2) );
}
我如何使用 std::arrays 做到这一点?
void func( ??? itBegin, ??? itEnd );
void main() {
std::array<T,1> arr1;
func( std::begin(arr1), std::end(arr1) );
std::array<T,2> arr2;
func( std::begin(arr2), std::end(arr2) );
}
问题是,在 MSVC 2010 中,std::array<T,N>::iterator
不同N
不同.这是 MSVC 2010 中的错误吗?如果不是,这种设计的基本原理是什么?是的,我可以从 std::array 获取指针并传递它们而不是迭代器,但这不是不必要的丑陋吗?
顺便说一句,boost::array<T,N>::iterator
所有N
都是一样的.
最佳答案
template <class I>
void func(I begin, I end)
{
for (auto x = begin; x != end; ++x)
something_with(*x);
}
将它们一般地定义为类型参数,然后就像使用指针一样使用它们。任何行为类似于指针的东西都会编译,否则不会编译。
类似指针的东西包括普通指针、标准库迭代器和任何其他定义 operator=
的东西, operator*
和 operator++
.
以这种方式进行操作,因为您只会使用来自相同 array<N>
的开始/结束迭代器范围的匹配对。 , 那么 array<N>::iterator
就没关系了是与 array<M>::iterator
不同的类型.
关于c++ - 没有模板的 std::array 迭代器范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10189191/