0

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

Community
  • 1
  • 1
HideTail
  • 3
  • 3
  • Do you mean `operator delete` or `delete_something`? `delete` is a keyword. – Potatoswatter Oct 07 '10 at 16:06
  • Welcome to SO :) Please use the "101010"-button or 4 space indent for your code to have it marked up as code. Like I just did for you :) – Magnus Hoff Oct 07 '10 at 16:10
  • I don't see what this is a duplicate of? In any case, what might be required in this case is simply two overloads (one that does nothing for non-pointers). And perhaps the class is trying to do too much - after all perhaps I don't want the class to manage my pointers? – UncleBens Oct 07 '10 at 16:30

2 Answers2

3

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

blahster
  • 2,043
  • 2
  • 14
  • 8
2

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
  • 134,909
  • 25
  • 265
  • 421
  • 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 Oct 07 '10 at 16:39
  • @HideTail: You shouldn't need to check anything. Overload resolution automatically determines which function to call. http://codepad.org/AgTVISzv – UncleBens Oct 07 '10 at 17:05