Monday, April 14, 2008

Dependant names

Using a template argument as a template argument for something else sometimes doesn't work, for example the following code:

#include <iostream>

using namespace std;

template<class _prec=double>
class myclass {
public:

typedef int atype;
};

template<class _prec=double>
class myclass2 {
public:

_prec method() {
myclass<_prec>::atype t = 0;
return t;
}
};

int main() {

myclass2<> m;

}


Gives this compilation error under g++:

templateargasarg.cpp: In member function '_prec myclass2<_prec>::method()':
templateargasarg.cpp:17: error: expected `;' before 't'
templateargasarg.cpp:18: error: 't' was not declared in this scope


It's something to do with dependant names, google it. I don't fully understand it. All I know is that as usual a typename fixes it i.e.:

    myclass<_prec>::atype t = 0;


becomes:

   typename myclass<_prec>::atype t = 0;


and all is well. My comp.lang.c++ thread is here.

No comments: