Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return pointer to nested inner class from generic outer class

I'm new to C++, so bear with me. I have a generic class called A. A has a nested class called B. A contains a method called getB(), which is supposed to return a new instance of B. However, I can't get my code to compile. Here's what it looks like:#include

A.h

template <class E>
class A {

public:
    class B {
    public:
        int data;
    };

    B * getB(); 
};

A.cpp

#include "A.h"

template <class E>
A<E>::B * A::getB() {
    return new B();
}

When I try to compile this, I get the following error:

error: expected constructor, destructor, or type conversion before '*' token

Does anybody know what I'm doing wrong?

Thanks,

helixed

UPDATE:

Thanks for the quick replies everyone. I'm still having a little trouble getting this working. After taking the suggestions listed here, I have something like this:

A.h

template <class E>
class A {

public:
    class B {
    public:
        int data;
    };

    B * getB(); 
};

template <class E>
typename A<E>::B * A<E>::getB() {
    return new B();
}

class C {

};

However, when I try to use this from main, I get an error. Here's my main method:

main.cpp

#include "A.h"

int main(int argc, char *argv[])
{
    A<C> *a = new A<C>();
    A<C>::B *b = a.getB();
}

When I try to compile this, I get the following error:

error: request for member 'getB' in 'a', which is of non-class type 'A<C>*'

Thanks again for the quick responses.

helixed

like image 404
LandonSchropp Avatar asked Apr 06 '10 19:04

LandonSchropp


2 Answers

The compiler isn't smart enough to figure that "B" is a type when "A" is templated. Try using typename.

template <class E>
typename A<E>::B * A<E>::getB() {
    return new B();
}
like image 140
Stephen Avatar answered Oct 07 '22 13:10

Stephen


You need to use typename in your definition to hint to the compiler that B is a type.

template <class E>
typename A<E>::B * A::getB() {
   return new B;
}
like image 33
Nick Meyer Avatar answered Oct 07 '22 14:10

Nick Meyer