views:

96

answers:

2

Possible Duplicate:
Determine if Type is a pointer in a template function

I am looking for a method to determine whether a template is a pointer or not at compiling time. Because when T is not a pointer, the program will not compile as you cannot delete a normal type variable.

template <typename T>
void delete(T &aVar)
{
   // if T is a point
   delete aVar;
   aVar = 0;
   // if T is not a point, do nothing
}

Basically, I am learning to create a link list(not using the STL list) myself. And I tried to use template in my list so it can take any types. When the type is a pointer, I want to delete it (the keyword delete) automatically by the destructor.

The problem is, as writen above, when I use int rather than some pointer of a class in the list, VC2010 wont compile because you cannot delete an none pointer variable. So I am looking for a method, such as macro to deceide when delete aVar should be compiled or not according to the template type

+2  A: 

That is a handy utility, but I think it's better just to get used to assigning NULL after using native delete.

To get a function that only is considered for modifiable pointer type arguments, use

template< typename T > // The compiler may substitute any T,
void delete_ref( T *&arg ); // but argument is still a pointer in any case.

To simply find out whether a type is a pointer, use is_pointer from <type_traits> in Boost, TR1, or C++0x.

Potatoswatter
Thanks for the is_pointer, I will try to overload my class and use is_pointer to determine which one to use, pointer one or not.
HideTail
@HideTail: You shouldn't need to check anything. Overload resolution automatically determines which function to call. http://codepad.org/AgTVISzv
UncleBens
+3  A: 

How about having that function taking a T* instead of T?

blahster
sellibitze