Here is a simplified example:
template<typename T>
class MyTemplate
{
class Inner {};
Inner met();
};
template<typename T>
MyTemplate<T>::Inner MyTemplate<T>::met()
{ }
I get the following compilation error:
expected constructor, destructor, or type conversion before 'met'
I use GCC. It seems the compiler doesn't recognize MyTemplate<T>::Inner
as a proper class. How can I fix this? I've tried sticking the typename
keyword here and there to no avail. Right now, the only way I can manage to compile this is to inline the method definition in the class declaration, which I would like to avoid.
To instantiate a template class explicitly, follow the template keyword by a declaration (not definition) for the class, with the class identifier followed by the template arguments. template class Array<char>; template class String<19>; When you explicitly instantiate a class, all of its members are also instantiated.
Templates are very useful when implementing generic constructs like vectors, stacks, lists, queues which can be used with any arbitrary type. C++ templates provide a way to re-use source code as opposed to inheritance and composition which provide a way to re-use object code.
Templates in c++ is defined as a blueprint or formula for creating a generic class or a function. Generic Programming is an approach to programming where generic types are used as parameters in algorithms to work for a variety of data types.In C++, a template is a straightforward yet effective tool.
template <typename T> ... This means exactly the same thing as the previous instance. The typename and class keywords can be used interchangeably to state that a template parameter is a type variable (as opposed to a non-type template parameter).
Clang reports the following:
error: missing 'typename' prior to dependent type name
'MyTemplate<T>::Inner' MyTemplate<T>::Inner MyTemplate<T>::met()
^~~~~~~~~~~~~~~~~~~~ typename 1 error generated.
And placing typename
in the appropriate place fixes it.
template<typename T>
class MyTemplate
{
class Inner {};
Inner met();
};
template<typename T>
typename MyTemplate<T>::Inner MyTemplate<T>::met()
{ }
Did you put typename in the correct location? If so, then this must be a bug in G++.
The return type of MyTemplate::met
is a dependent name, so you need to add the typename
keyword before it. The following compiles on gcc-4.5.1
template<typename T>
struct MyTemplate
{
class Inner {};
Inner met();
};
template<typename T>
typename MyTemplate<T>::Inner MyTemplate<T>::met()
{
return typename MyTemplate<T>::Inner();
}
int main()
{
MyTemplate<int> foo;
MyTemplate<int>::Inner bar = foo.met();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With