Why does the following code give me an error (g++ 4.1.2)?
template<class A>
class Foo {
public:
typedef std::vector<A> AVec;
AVec* foo();
};
template<class A>
Foo<A>::AVec* Foo<A>::foo() { // error on this line
return NULL;
}
The error is:
error: expected constructor, destructor, or type conversion before '*' token
How am I supposed to define the Foo<A>::foo() function otherwise (with the correct return type)?
This is an issue called “two-stage lookup“. Basically, since
Ais a template parameter infoo()‘s definition, the compiler can’t know when parsing the template for the first time, whetherFoo<A>::AVecis a type or even exists (since, for instance, there may exist a specialization ofFoo<Bar>which doesn’t contain the typedef at all). It will only know what it is during template instantiation, which happens later – and it’s too late for this stage.The correct way would be to use the
typenamekeyword to indicate that this is a type: