4

Is there a correct way of defining a member function for a template class, that returns an instance of a subclass?

Here's an example that does not compile in VC++ 2010:

template<class T> class A {
public:
    class B {
    public:
        T i;
    };

    A();
    B* foo();
};

/////////////////////////////////////////////

template<class T> A<T>::A() {}

template<class T> A<T>::B* A<T>::foo() {
    cout << "foo" << endl;
    return new B();
}

I get

Error   8   error C1903: unable to recover from previous error(s); stopping compilation 

at the line where the definition of foo starts.

I have the correct inclusions and namespace declarations for iostream etc.

Thanks guys!

Edit:

As requested, here's the complete list of errors, all at the same line:

Warning 1   warning C4346: 'A<T>::B' : dependent name is not a type
Error   2   error C2143: syntax error : missing ';' before '*'
Error   3   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error   4   error C1903: unable to recover from previous error(s); stopping compilation
Warning 5   warning C4346: 'A<T>::B' : dependent name is not a type
Error   6   error C2143: syntax error : missing ';' before '*'
Error   7   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
Error   8   error C1903: unable to recover from previous error(s); stopping compilation
Mau
  • 13,256
  • 2
  • 28
  • 49
  • Give us "previous error(s)" too. Maybe typename before A::B is missing? – PiotrNycz Jul 10 '12 at 13:50
  • Thanks @PiotrNycz, please see edit. – Mau Jul 10 '12 at 14:03
  • possible duplicate of [Where and why do I have to put the "template" and "typename" keywords?](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) – Mike Seymour Jul 10 '12 at 15:05

1 Answers1

5

Name A<T>::B is depedent , you need to hint the compiler that depedented name is type

template<class T> typename A<T>::B* A<T>::foo() {...}

same for this line : return new B(); -> return new typename A<T>::B();

Read: Where and why do I have to put the "template" and "typename" keywords?

Community
  • 1
  • 1
Mr.Anubis
  • 4,824
  • 5
  • 27
  • 43