简体   繁体   English

std :: array迭代器范围没有模板?

[英]std::array iterator range without template?

With C arrays, it is fairly easy to write code that takes arrays of any size: 使用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) );
}

How can I do that with std::arrays? 我怎么能用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) );
}

The problem is that, in MSVC 2010, std::array<T,N>::iterator is different for different N . 问题是,在MSVC 2010中, std::array<T,N>::iterator对于不同的N是不同的。 Is this a bug in MSVC 2010? 这是MSVC 2010中的错误吗? If not, what is the rationale of this design? 如果没有,这个设计的理由是什么? Yes, I could get pointers from the std::array and pass them instead of iterators, but isn't that unnecessarily ugly? 是的,我可以从std :: array获取指针并传递它们而不是迭代器,但这不是不必要的丑陋吗?

BTW, boost::array<T,N>::iterator are the same for all N . BTW, 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);
}

Define them genericly as a type parameter, and then just use them as if they were pointers. 通常将它们定义为类型参数,然后只需将它们用作指针即可。 Anything that behaves pointer-like will compile, things that don't, won't. 任何行为类似指针的东西都会编译,而不会发生的东西则会编译。

Pointer-like things include normal pointers, as well as standard library iterators, and anything else that defines operator= , operator* and operator++ . 类似指针的东西包括普通指针,标准库迭代器,以及定义operator=operator*operator++任何其他东西。

Doing it this way and as you will only ever use matching pairs of begin/end iterator ranges from the same array<N> , then it doesn't matter if array<N>::iterator is a different type to array<M>::iterator . 这样做是因为你只使用匹配的同一个array<N>的开始/结束迭代器对,那么如果array<N>::iterator是一个与array<M>::iterator不同的类型array<M>::iterator

As far as I can tell, the standard doesn't require that different sized std::array have the same type of iterator; 据我所知,标准不要求不同大小的std::array具有相同类型的迭代器; having a different type for std::array<int, 1> and std::array<int, 2> seems legal (although one might have some opinions with regards to the quality of the implementation). 具有std::array<int, 1>std::array<int, 2>的不同类型似乎是合法的(尽管可能对实现的质量有一些看法)。

If this is a problem, you can either use a C style array, or use pointers: 如果这是一个问题,您可以使用C样式数组,也可以使用指针:

func( &arr1[0], &arr1[0] + arr1.size() );

Neither solution is ideal, but they're the best I can offer. 这两种解决方案都不是理想的,但它们是我能提供的最好的解决方案。

template <class I>
void func(I begin, I end);

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

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