Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ returning nested class with template on base class problem

I am trying to create a list object, with the iterator class nested inside to understand how it works. In some method, I am trying to return an iterator object but it doesn't work. I created an example to show the problem :

// CLASS A
template <class T>
class A
{
    public:
        class B;
        A(){}
};

// CLASS B
template <class T>
class A<T>::B
{
    private:
        int varB;

    public:
        B(B& b);
        B(const int&);
        B returnThis();
};

template <class T>
A<T>::B::B(const int& value)
{
    varB = value;
}

template <class T>
A<T>::B::B(B& b)
{
    varB = b.varB;
}

template <class T>
A<T>::B A<T>::B::returnThis()
{
    return *this;
}

// MAIN

void main()
{
    A<int>::B classB(10);
}

The error is near those lines:

template <class T>
A<T>::B A<T>::B::returnThis()

The compiler tells me I am missing a ; before A::B::returnThis()

I am trying to solve this problem for days and I can't find a way to make it work... I would really appreciate some help. Thanks in advance!

like image 655
Vallières Avatar asked Nov 27 '09 21:11

Vallières


1 Answers

You need typename:

typename A<T>::B

To indicate to the compiler that A<T>::B is a type. Here's a good explanation why.

What B is depends on what A<T> is, this is called dependency. Any time you are getting a type out of a class or struct, and it's dependent on a template, you'll need to use typename.

like image 50
GManNickG Avatar answered Oct 07 '22 12:10

GManNickG