具有指针类型和常规类型的类模板 [英] Class template with both pointer type and regular type
问题描述
我用值类型的模板定义一个Node类
I define a Node class with template for its value type
template<class T>
class Node {
T val;
public:
Node (T & v) : val (v) {}
...
void print() { cout << v << endl; }
}
在大多数情况下,感兴趣的节点值将是一个对象类,例如class Foo
.在这种情况下,使用Node<Foo *>
会更方便.但是也可能是该节点将保留原始时间,例如int
.然后使用Node<int>
就足够了.
Most times, the node value of interest will be an object class, say class Foo
. In that case, use Node<Foo *>
will be more convenient. But it could also be that the node will hold primitive time, say int
. Then use Node<int>
will suffice.
问题是,某些功能可能需要根据T
是否为指针类型而有所不同.例如,print
应当为cout << *v
,否则为cout << v
.
The problem is, some of the function may need to behave differently based on whether T
is a pointer type or not. For example, print
should cout << *v
when it is and cout << v
otherwise.
我试图定义两者:
template<class T>
class Node {
T val;
public:
Node (T & v) : val (v) {}
...
void print() { cout << v << endl; }
}
template<class T>
class Node<T*> {
T* val;
public:
Node (T* v) : val (v) {}
...
void print() { cout << *v << endl; }
}
现在它可以根据是否为Node<int> or Node<int *>
选择适当的定义,但是问题是,这两个定义将共享许多代码.我想知道是否有更好的方法来实现这一目标.
It now can choose the appropriate definition based on whether it's Node<int> or Node<int *>
But the problem become, the two definitions will share many code. I'm wondering whether there's better way to achieve this.
推荐答案
请参见:此处应使用相同的技术,在这两种情况下,您都可以将val
作为参考(或指针)统一处理.
The same technique should work here, allowing you to deal with the val
as a reference (or a pointer) uniformly in both cases.
CRTP 可以帮助减少代码重复,从而允许两个专业化的通用代码而没有任何开销,也是如此.
CRTP may help reduce code duplication, allowing for common code for two specializations without any overhead, as well.
请注意,当您有时使用指针而有时使用实例时,所有权语义会变得棘手-如果val
有时是参数的指针,而有时又是参数的副本,那么val
的寿命是多少,以及如何执行?
Note that ownership semantics get tricky when you sometimes use a pointer and sometimes an instance -- what is the lifetime of val
if sometimes it is a pointer of an argument, and other times it is a copy of the argument, and how to you enforce it?
这篇关于具有指针类型和常规类型的类模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!