dde*_*mez 2 c++ templates pointers
在编写模板类win C++时,我遇到了一个小问题.问题很简单:我不知道是否要delete在paremetrized类型上做一个,因为它可能,或者它不能成为一个指针.
我已经看到了这样:模板类c中的析构函数:如何删除可能是指针或非指针的字段?
我已经实现了第一个解决方案,但这需要我专门化整个类,所以这意味着我必须有两个类:
template<class T>
class Node {
private:
T _content;
public:
Node(const T c);
~Node();
};
Run Code Online (Sandbox Code Playgroud)
和
template<class T>
class Node<T*> {
private:
T _content;
public:
Node(const T c);
~Node();
};
Run Code Online (Sandbox Code Playgroud)
我想只有第二个版本,并且只对析构函数进行如下操作:
template<class T>
class Node<T*> {
private:
T _content;
public:
Node(const T c);
~Node();
};
template <class T>
Node<T>::~Node() {
while(!_adjacent.isEmpty()) {
disconnectFrom(_adjacent.first());
}
}
template <class T>
Node<T*>::~Node() {
while(!_adjacent.isEmpty()) {
disconnectFrom(_adjacent.first());
}
delete _content;
}
Run Code Online (Sandbox Code Playgroud)
但后来我收到以下错误:
Node.hpp:43:17: error: invalid use of incomplete type ‘class Node<T*>’
Node.hpp:8:7: error: declaration of ‘class Node<T*>’
Run Code Online (Sandbox Code Playgroud)
有没有办法专门化构造函数以避免有2个类(我的Node类比我在这里展示的要大得多)?
谢谢!
解决方案是使用traits类:
template<typename T> struct delete_traits
{
void destroy(T&) {}
};
template<typename T> struct delete_traits<T*>
{
void destroy(T* p) { delete p; }
};
Run Code Online (Sandbox Code Playgroud)
然后在你的类析构函数中写
delete_traits<T>::destroy(_contents);
Run Code Online (Sandbox Code Playgroud)
除了不必专门化Node模板之外,它还有一个额外的好处,即您可以轻松添加其他方法来破坏事物,而无需触及您定义的文件Node,只需添加另一个模板专门化:
// assumes that mylib_handle is a truly different type, maybe a C struct
// from the C interface of a library
template<> struct delete_traits<mylib_handle>
{
void destroy(mylib_handle& h) { mylib_handle_free(m); }
};
Run Code Online (Sandbox Code Playgroud)