Access to protected member variable from derived inner class in a templated parent class

Viewed 60

I'm getting this error when trying to compile this:

template <typename T>
struct Temp
{
    struct BaseIterator
    {
    protected:
        int  pos;
        BaseIterator() : pos(0) {}
    };

    struct LeafIterator : public BaseIterator
    {
        int * operator * () { return &pos; }

        LeafIterator() : BaseIterator() {}
    };
};

Returns:

prog.cpp: In member function ‘int * Temp<T>::LeafIterator::operator*() const’:
prog.cpp:24:52: error: ‘pos’ was not declared in this scope
             int * operator * () { return &pos; }

The same code without the parent Temp structure works fine, and so does the code when the Temp structure is not template. Similarly, even if the base's member is public, I still get the compiler's error.

I know that I can refer to inherited members via this->pos, but it's a real pain to add this-> everywhere in the code.

How can I access the base members without having to prefix all of them via this-> ?

Edit: The BaseIterator is simply holding common member for many different (but working similarly) iterators. I can duplicate all members in all iterators and be done with it, but I wanted to reuse a common/generic interface.

2 Answers

How can I access the base members without having to prefix all of them via this-> ?

You can create a private accessor:

class LeafIterator : public BaseIterator
{
private:
    int& pos() { return this->pos; }

public:
    int * operator * () { return &pos(); }

    LeafIterator() : BaseIterator() {}
};

You can use a using declaration.

template <typename T>
struct Temp
{
    struct BaseIterator
    {
    protected:
        int  pos;
        BaseIterator() : pos(0) {}
    };

    struct LeafIterator : public BaseIterator
    {
        using BaseIterator::pos;
        int * operator * () { return &pos; }

        LeafIterator() : BaseIterator() {}
    };
};

int main()
{
    Temp<int>::LeafIterator leaf_iterator;
}

This compiles fine in GCC 8.2.0.

Related