I have a first class A that contain an iterator nested class with virtual methods:
template <typename T >
class A {
public:
class iterator {
public:
virtual ~iterator() {};
virtual T& operator++();
};
virtual iterator begin() const = 0;
};
I have a second class B, that override virtuals methods:
template <typename T >
class B : public A<T> {
public:
class iterator : A<T>::iterator {
T& operator++() override {
iterator p(*this);
return p; //for exemple
}
};
iterator begin() const override {
return iterator(this);// for exemple
}
};
But when i use B class :
B<int> test;
I have something like this, compilation error:
error: invalid covariant return type for 'B<T>::iterator B<T>::begin() const [with T = int]'
error: overriding 'B<T>::iterator V<T>::begin() const [with T = int]'
How to implements iterator in B class ?
Co-variant return types have a couple of constraints they need to satisfy according to [class.virtual]/8.
Yours doesn't inherit publicly, so the base isn't accessible. And you aren't returning a pointer or a reference.
Returning a type with value semantics is good! You should not give up on that. You can substitute the attempt at a co-variant return type with the pimpl idiom. Have
iteratormanage a polymorphic "iterator implementation" class via pointer.