Hi,
I have a couple of questions:
1) How would you create a header file with full of
function templates
with declaration and definition separately... Is it possible to write the declarations in the .h file and definitions in the .cpp file (as we would do if not using templates?
2) Suppose I have implemented a basic vector class (including all operator overloading). Now, if I have to implement certain "utility functions".. for example, find the
unique
elements of a vector (created using this class of course), how I go about is creating a
function template
(in a separate header, say widgets.h) as,
1 2 3 4 5 6 7 8 9 10
|
#include "vector_class.h"
template <class T>
vec<T> unique(vec<T> &v) {
vec<T> unique_v;
// code to obtain the unique elements
return unique_v;
}
|
As you can see, this code definitely requires creating a vector and returning it. This might be disadvantageous if the size of the vector is huge. I see 2 other possibilities.
a) in some cases, it might be possible (or make sense) to frame the algorithm in a way to store the result in the calling object itself (for ex: sort). This solves both the issues.
b) Implement it as a member function and all
v.unique();
, return using the *this pointer. This will also change the contents of the calling object.
Are they both equally good? (unless there is a third better option). Or do you think returning a vector isn't as bad as it sounds..?
PS: I have been advised that creating a pointer object (in the function template described above) and returning the address is also possible, but is not generally recommended as the user will have to take the task of freeing the pointer ?? I don't quite get a hold of it as to why. Could you show the code and tell how/why its so.
Thank you very much!