After creating a templated C++ class that takes an integer in a header file, I found that Eclipse would not recognise my method implementations in the corresponding .cpp file.
Here's an example class that takes a size template parameter:
template <int SIZE>
class SizeableClass
{
public:
SizeableClass();
virtual ~SizeableClass();
};
I told Eclipse to generate the implementation bodies for me with Source => Implement Method...
It produced some inline methods in the header file. I moved them to the .cpp file for tidiness and removed the inline
qualifier. My .cpp file now looked like this:
template<int SIZE>
SizeableClass<>::SizeableClass()
{
}
template<int SIZE>
SizeableClass<>::~SizeableClass()
{
}
But this was underlined in red with the "Member declaration not found" error. It won't compile with gcc
either:
SizeableClass.h:2:7: error: provided for ‘template<int SIZE> class SizeableClass’
class SizeableClass
^
What's wrong about it?
The Eclipse generator seems to have missed out a key part of the implementations. This would have the same problem even if they weren't moved out of the header file.
Usually, templates are used with typenames such as:
template<typename T>
SizeableClass<T>::SizeableClass()
{
}
template<typename T>
SizeableClass<T>::~SizeableClass()
{
}
So it's forgivable to think that if you're not using typenames there doesn't need to be anything between the angular brackets (<>
).
However, in this case, the SIZE
template parameter needs to go in those brackets. The .cpp file should read:
template<int SIZE>
SizeableClass<SIZE>::SizeableClass()
{
}
template<int SIZE>
SizeableClass<SIZE>::~SizeableClass()
{
}
// Additionally, if there are any methods that return SizeableClass, they also need to be parametrized
template<int SIZE>
SizeableClass<SIZE> SizeableClass<Size>::myMethod()
{
}
As a side note, this won't compile properly when linking the program. Since the functions are templates and not actual implementations, every class that includes the header file will also need to see the template definitions. This can be fixed by making the functions inline
again and either putting them in the header file or including them.