Reputation: 3326
In the following code, I get a compile error that I don't have if I remove the templates :
template<int DIM> class myClass
{
public :
enum Mode {aa,bb};
myClass(){};
};
template<int DIM> class myClass2
{
myClass2(){};
void myfunc(myClass::Mode m);
};
template<int DIM>
void myClass2<DIM>::myfunc(myClass<DIM>::Mode m)
{
}
test.cpp(19) : warning C4346: 'myClass::Mode' : dependent name is not a type
prefix with 'typename' to indicate a type
test.cpp(19) : error C2146: syntax error : missing ')' before identifier 'm'
If I remove the like:
template<int DIM>
void myClass2<DIM>::myfunc(myClass::Mode m)
I get :
test.cpp(19) : error C2955: 'myClass' : use of class template requires template argument list
And if I put the definition of myfunc
directly in the declaration of the class (which I would like to avoid), it works.
What should I do and why does this happen?
Thanks
Upvotes: 2
Views: 280
Reputation: 3509
Here you go...
template<int DIM> class myClass
{
public :
enum Mode {aa,bb};
myClass(){};
};
template<int DIM> class myClass2
{
myClass2(){};
// you need to pass the template parameter to myClass
// "typename" needs to be present when using types from templated classes
// from within a templated class/function.
void myfunc(typename myClass<DIM>::Mode m);
};
template<int DIM>
void myClass2<DIM>::myfunc(typename myClass<DIM>::Mode m)
{
}
Upvotes: 1
Reputation: 373462
I believe that you have two problems in your code. The first is in this declaration in myClass2
:
void myfunc(myClass::Mode m);
Because myClass
is a template, you need to specify what the template parameter is. I assume that you probably meant to write
void myfunc(myClass<DIM>::Mode m);
However, due to a weird idiosyncrasy in C++, you would write this as
void myfunc(typename myClass<DIM>::Mode m);
The typename
keyword here tells C++ that Mode
is the name of a type nested inside of the class myClass<DIM>
.
Similarly, later in the code, the code
template<int DIM>
void myClass2<DIM>::myfunc(myClass<DIM>::Mode m)
{
}
should read
template<int DIM>
void myClass2<DIM>::myfunc(typename myClass<DIM>::Mode m)
{
}
to tell the compiler that Mode
is the name of a type.
Hope this helps!
Upvotes: 6