C++ iterating over a class that wraps around a list

91 Views Asked by At

Sorry for such a bad title but I don't know how to condense what I want to say. Anyway, I have a template class that wraps around a list, something simple like this:

template<typename T>
class MyWrapper {
    std::list<T> items;
}

I want to be able to use this wrapper in a foreach loop. As my class is simply wrapping a list (i.e. it's not really a custom collection), I think I can just use that list's iterator functions as my own:

typename _Container::iterator begin () noexcept {
    return items.begin();
}

typename _Container::iterator end () noexcept {
    return items.end();
}

typename _Container::const_iterator cbegin () const noexcept {
    return items.cbegin();
}

typename _Container::const_iterator cend () const noexcept {
    return items.cend();
}

This works fine for non-const instantiations of my class, but not for const-ones. Example:

// this one works fine and iterates the inner list as you'd expect.
MyWrapper& mywr = someMethod(); // returns MyWrapper&
for (auto& el : mywr) {
    //...
}

// this one won't compile
const MyWrapper& myconst = someConstMethod(); // returns const MyWrapper&
for (const auto& el : myconst) {
    //...
}

The error given is "no instance of function "MyWrapper::begin" matches the argument list and object (the object has type qualifiers that prevent a match) - object type is: const MyWrapper".

As this should be a pretty common use case, I'm sure there's a page specifying exactly which methods to implement to get this working, but I haven't been able to find it so far.

0

There are 0 best solutions below