c++arraysc++14const-iterator

std::array::iterator that ignores the size template


I am implementing a function that wants to loop over a number of elements in an std::array, but I don't really care how long the std::array is. So I was thinking of the following function:

#include <stdio.h>
#include <array>
#include <iterator>

void foo(std::array<bool,0>::const_iterator begin, std::array<bool,0>::const_iterator end)
{
    printf("iterator");
}

int main()
{
    std::array<bool, 25> one;
    std::array<bool, 33> two;

    foo(one.cbegin(), one.cend());
    foo(two.cbegin(), two.cend());
}

I am quite okay with this, except for the std::array<bool,0>. My question is, is there another way to specify the iterator that is required for this function?


Update

There are some things I should mention. Of course this code is part of a bigger scope and I tried to hide as much detail as I could.

  1. I want to ensure that the iterator being used is of bools.
  2. I am using C++14
  3. The function is part of a class interface and I want to be able to handle multiple array sizes. I don't want to bother the implementors of the interface to know exactly what the size of the array is.
class MyInterface
{
public:
    virtual foo(std::array<bool,0>::const_iterator begin, std::array<bool,0>::const_iterator end) = 0;

    ~MyInterface() = default;
};

I remembered that virtual functions cannot be templated. That means I would have to template my whole interface and that would exactly loose the point of why I was trying this in the first place.


Solution

  • You can just make it a function template as

    template <typename I>
    void foo(I begin, I end)
    {
        std::cout << "iterator";
    }
    

    You don't need to care about container type (and the size), you can pass iterators of std::array, std::vector and std::string and so on, even raw pointers (which also satisfies iterator's requirements).