Nested class inside an abstract class

I have an abstract class:

class A
{
public:
    void func() = 0;
};

Can I make my implementations also have a nested iterator class?

#include <iterator>

template<typename T>
class A
{
public:
    class Iterator : public std::iterator<std::forward_iterator_tag, T>
    {
    };

    virtual Iterator begin() const = 0;
    virtual void func() = 0;
};

template<typename T>
class B : public A<T>
{
public:
    B() {}
    class Iterator : public std::iterator<std::forward_iterator_tag, T>
    {
    };

    Iterator begin() const
    {
        return Iterator();
    }

    virtual void func()
    {
    }
};

int main()
{
    B<int> b;
}

I just want to know if this is possible, and if so, what am I missing? Since the iterator class will depend on how class A is implemented, I don't know if formal implementation is possible.

+4
source share
2 answers

Try the following:

template<typename T>
class A
{
public:
    class Iterator : public std::iterator<std::forward_iterator_tag, T>
    {
    public:
        virtual void DoSomething() = 0;
    };

    virtual Iterator * begin() const = 0;
    virtual void func() = 0;
};

template<typename T>
class B : public A<T>
{
public:
    B() {}
    class BIterator : public A<T>::Iterator
    {
    public:
        void DoSomething()
        {
            std::cout << "Hello world from B::BIterator!";
        }
    };

    A<T>::Iterator * begin() const
    {
        return new BIterator();
    }

    virtual void func()
    {
    }
};

int main(int argc, char * argv[])
{
    B<int> b;

    A<int>::Iterator * iter = b.begin();
    iter->DoSomething();
    delete iter;

    getchar();
}

, B A<T>::Iterator, . , , A<T> - . , , ?


:

. , , :

A<int>::Iterator iter = b.begin(); // Error: cannot instantiate abstract class
                                   // A<int>::Iterator

, , A<T>::Iterator, . A<T>::Iterator...

+3

, , , ?

, , - Iterator, .

, , - . , , , .

, , Container: , T :

  • ...
  • T::reference
  • T::const_reference
  • T::iterator
  • ...

, :

template<class Container>
void do_something(Container c) {
    Container::iterator it = c.begin();
    // etc
}

, , Container. , ( vector, list deque).

, , ++, , , , , , . , , .

, Lite, "".

+1

Source: https://habr.com/ru/post/1531131/


All Articles