I have got this code and I am trying to understand the convention followed, all the method defined in the .cpp file have template<class KeyType, class DataType> written before them. What does that mean?
Example:
//Constructor
template<class key, class type>
MyOperation<key, type>::MyOperation()
{
//method implementation
}
//A method
template<class key, class type>
MyOperation<key, type>::otherOperation()
{
//method implementation
}
Thanks
There has to be a good answer for this already but I’ll throw mine into the pool as well.
C++ allows for declarations and implementations of program structures to be done separately. It stems from how C/C++ programmers publish new functionality to each other: header files are included in dependent compilation units rather than those units relying on metadata present in compilation (like you would expect if you work with C# or Java).
Each time you give the compiler an instruction whether it is a declaration (“there will be this thing with this interface”) or an implementation (“here is this thing with this interface and these behaviors”), you have an opportunity to templatize that directive.
The fact that you have an option to do so, rather than a requirement to do so, gives you a lot more flexibility than you are afforded by more modern languages such as Java and C#.
Consider the following template (I’m rusty so be kind with minor syntax issues, please):
Your “typical” implementation of said template might include these default behaviors:
However, for strings, there is a risk that the string will be modified after the pointer is copied, in which case, you could provide a specialized behavior that ensures the string itself is copied, rather than the pointer (again, it’s been a long, long time)…
You could then do something similar for GetJunk(). That is probably why you have to declare the template parameters for each artifact you create: because you might not want them to be the same in every case.