开发者

C++ whether a template type is a pointer or not [duplicate]

This question already has answers here: Closed 12 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜