C++模板问题
template <class T>
class ListNode {
public:
T* data;
ListNode<T>* next;
}
假设我有一个列表节点模板,并且在代码中的某个位置我想获取数据的副本 - 这意味着不是指向数据的指针 (T*) 的副本,而是一个指向另一个的新指针 (T*)内存中具有相同信息的位置。
使用C++模板时如何做到这一点?如果我不知道 T 的类型是什么,如何复制 (*data)。
template <class T>
class ListNode {
public:
T* data;
ListNode<T>* next;
}
Lets say I have got a list node template and somewhere in the code I want to get a copy of the data - meaning not a copy of a pointer to data (T*) but a new pointer (T*) which will point to another place in the memory which have the same information there.
How can I do it when using C++ templates? How can I copy (*data) if I don't know what is the type of T.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
编译器知道T的类型。不知道的是有多少个 T 实例被指向。就获得实际实现而言,简短的答案是不要使用指针类型。请改用容器。由于无论如何都要复制节点数据,因此开销很小。下面是明确的示例:
实际用法与此类似:
当然,您可以得到更复杂的解决方案,但它们都将涉及跟踪指针指向的类型 T 的实例数量。
The compiler knows the type of T. What is does not know is how many instances of T are pointed to. In terms of getting a practical implementation, the short answer would be don't use pointer types. Use containers instead. Since you are copying the node data anyway the overhead is minimal. Explicit example below:
Actual usage would be similar to this:
You can, of course, get much more complicated solutions but they will all involve keeping track of the number of instances of type T to which your pointer points.
T 必须是可复制构造的,这样您就可以执行
如果 T 有复制构造函数,则这将起作用。如果没有,编译器会给你一个错误(可能是一个非常神秘的错误)
T has to be copy-constructable so that you can do
If T has a copy constructor, this will work. If it doesn't, the compiler will give you an error (probably a very cryptic one)
使用运算符=或复制构造函数。标准做法是,这两者都会生成对象的副本。
因此,例如:
或者
Use operator= or the copy constructor. It's standard practice that both of these will produce a copy of the object.
So, for example:
Or
创建模板化类型的副本时,实际上您无需担心类型本身,而是在该类型的复制构造函数或赋值运算符上执行该任务:
假设您使用此
ListNode
class A
,那么您可以为 A 定义一个复制构造函数(以及赋值运算符):现在,当调用
ListNode::getCopy()
时,它将在内部调用 A 的复制构造函数。When creating a copy of a templated type, practically you need not worry about the type as such and live that task on the copy constructor or assignment operator of that type:
Suppose you use this
ListNode<T>
forclass A
, then you can have a copy constructor defined for A (and assignment operator as well):Now when
ListNode<T>::getCopy()
is called, it will call the copy constructor of A internally.