Re: Overloading on a pointer and an array type
"Bart van Ingen Schenau" <bart@ingen.ddns.info> schrieb im Newsbeitrag
news:9485383.nPOeAJ2rxQ@ingen.ddns.info...
Matthias Hofmann wrote:
/* Helper struct to obtain the element type of an array */
template <class T> struct get_element_type;
template <class T, size_t N> struct get_element_type<T[N]>
{
typedef T type;
};
Great, this is just the solution to a problem I had with having a template
function forward the call to helper classes to emulate function template
partial specialization! :-) Here's the new code:
#include <cstddef>
#include <iostream>
// Extracts the type of an object.
template <class T>
struct extract { typedef T type; };
// Extracts the type of an array.
template <class T, std::size_t N>
struct extract<T[N]> { typedef T type; };
// Primary template for object new.
template <class T> struct TrackNewHelper
{
static T* TrackNew( T* ptr, const char* file, int line)
{
std::cout << "Tracking object allocation" << std::endl;
return ptr;
}
};
// Partial specialization for array new.
template <class T, std::size_t N> struct TrackNewHelper<T[N]>
{
static T* TrackNew( T* ptr, const char* file, int line)
{
std::cout << "Tracking array allocation " << std::endl;
return ptr;
}
};
// Forwards the call to helper classes.
template <class T> typename extract<T>::type* TrackNew(
typename extract<T>::type* ptr, const char* file, int line )
{
return TrackNewHelper<T>::TrackNew( ptr, file, line );
}
#define NEW( T ) TrackNew<T>( new T, __FILE__, __LINE__ )
int main()
{
int * p = NEW( int ); // Calls the primary template.
delete p;
p = NEW( int[64] ); // Calls the partial specialization.
delete [] p;
return 0;
}
Anyway, thank you very much for your solution! And if anyone is interested
in what my problem was, then try to implement the above without the
'extract' helper classes... ;-)
--
Matthias Hofmann
Anvil-Soft, CEO
http://www.anvil-soft.com - The Creators of Toilet Tycoon
http://www.anvil-soft.de - Die Macher des Klomanagers
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]