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

早过忘川 提交于 2021-02-08 12:45:08

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/1810622/c-returning-nested-class-with-template-on-base-class-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!