I’ve encountered some template code that doesn’t compile, and I’m not sure I understand why. The problem seems to be related to using an inner class with out-of-line method definition. The following is a simple example:
template<typename T>
class Outer {
public:
struct Inner {
T a;
Inner(T _a) : a(_a) {}
};
int foo(T a);
};
template<typename T>
Inner Outer<T>::foo(T a) { //Line 43
Inner ret(a);
return ret;
}
int main(int argc, char *argv[]) {
Outer<int> out;
return 0;
}
g++ 4.2.1 fails with the error: error: expected constructor, destructor, or type conversion before ‘Outer’ referring to line 43 marked above. The code works fine when I move the definition of foo to be inline.
I also tried replacing Inner with Outer<T>::Inner on line 43, but that did not make a difference.
Any thoughts?
You have two problems. First, you declared it to return an
int. But secondly, you needtypename Outer<T>::Innerif you want to access the Inner type outside the scope of Outer.