I want to implement a template function that has different behaviour for POD types (double, int, char, etc.) as opposed to actual structs or class types that can have constructors and destructors.
I could solve this by providing a generic function for all types:
template <class T> void alloc(T*& p, std::size_t size) {
p = reinterpret_cast<T*> ( malloc(size*sizeof(T)) );
new (p) T[size];
}
and then specialisations for all POD types:
template <> void alloc(double*& p, std::size_t size) {
p = reinterpret_cast<double*> ( malloc(size*sizeof(double)) );
}
However, I'd rather not copy/paste the same code all over again 6-8 times if I can avoid it.
So is there a better way to distinguish between POD types and others that doesn't force me to copy specializations all over again?
And before you ask, no, new and delete are not an option. I plan to implant my own memory manager here later. (and that will mean even more specalizations!)
P.S.:
For the sake of those wondering about the need for this in the view of some simple answers to the problem I outlined above:
The actual problems are more convoluted than the above example, including
- a class that passes on the template parameter through several function calls; therefore, even though the compiler does, I do not know the actual type at the point I call the allocator
- additional allocators that, among other things, provide the ability to pass an initializer value
- specializations for certain classes or even POD types (such as TCHAR) that need a particular treatment upon allocation or deallocation
The first issue is the most restricting one. The second I could cut down to whatever I can make work for now and expand later, if I find a solution. The last issue doesn't currently seem to be a problem in light of the question, but I haven't checked all cases yet.