How does one write a function in C++ that takes in as a parameter an iterator of a certain type in a container-agnostic way? i.e.
// C# version
void foo(IEnumerable<MyConcreteClass> t)
{
foreach(MyConcreteClass c in t)
{
c.MyFunction();
}
}
Reading about iterators it seems I'm supposed to do something like this:
template<MyIter>
void foo(MyIter start, MyIter end, std::input_iterator_tag type)
{
// How would the next part work? Do I do:
while (start != end)
{
MyConcreteClass* c = *start; // this will compile iff the parameter is correct.
c->MyFunction();
start++;
}
In the case of an invalid iterator type being passed in (e.g. a std::unordered_set<MyOtherClass*>::iterator
), I feel that the compiler error generated using this method would just be some sort of invalid cast error at the line where I dereference start
; I'd like instead to get an error that I'm actually passing in an iterator of the wrong type. Is there a better way to do this? I'd be nice to say "MyIter must be an iterator from a container of MyConcreteClass"
BTW, C++11 mechanisms are OK.