C++ 具有指针类型和常规类型的类模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14528902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Class template with both pointer type and regular type
提问by Oxdeadbeef
I define a Node class with template for its value type
我为它的值类型定义了一个带有模板的 Node 类
template<class T>
class Node {
T val;
public:
Node (T & v) : val (v) {}
...
void print() { cout << v << endl; }
}
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.
大多数时候,感兴趣的节点值将是一个对象类,比如class Foo
。在这种情况下,使用Node<Foo *>
会更加方便。但也可能是节点将保持原始时间,例如int
。那么使用Node<int>
就足够了。
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.
问题是,某些函数可能需要根据是否T
为指针类型来表现不同。例如,print
应该是cout << *v
什么时候,cout << v
否则。
What I've tried is to define both:
我尝试过的是定义两者:
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; }
}
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.
它现在可以根据是否可以选择合适的定义,Node<int> or Node<int *>
但问题变成了,这两个定义将共享许多代码。我想知道是否有更好的方法来实现这一目标。
采纳答案by Yakk - Adam Nevraumont
请参阅:C++ 模板特化,在可以明确为指针或引用的类型上调用方法
The same technique should work here, allowing you to deal with the val
as a reference (or a pointer) uniformly in both cases.
在这里应该使用相同的技术,允许您val
在两种情况下统一将用作引用(或指针)。
CRTPmay help reduce code duplication, allowing for common code for two specializations without any overhead, as well.
CRTP可能有助于减少代码重复,也允许在没有任何开销的情况下为两个专业提供通用代码。
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?
请注意,当您有时使用指针,有时使用实例时,所有权语义会变得棘手——val
如果有时它是一个参数的指针,其他时候它是一个参数的副本,那么它的生命周期是多少,以及如何强制执行它?
回答by Alok
Well, there is one more way of doing this. You should use type traits, they are evaluated at compile time. This is how you can modify.
好吧,还有一种方法可以做到这一点。您应该使用类型特征,它们在编译时进行评估。这是您可以修改的方式。
template<class T>
class Node {
T val;
public:
Node (T & v) : val (v) {}
...
void print() {
if(std::is_pointer<T>::value)
cout << *v << endl;
else
cout << v << endl;
}
}