C++ whether a template type is a pointer or not [duplicate]
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) automatica开发者_如何学Pythonlly 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
How about having that function taking a T* instead of T?
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.
精彩评论