C++不同子类的链接列表
C++ Linked List of Different SubClasses
我正在努力为一个项目制作内存池,但是我在编译它时遇到了问题:
我有一个内存池类(在下面的 R 示例中),它有一个模板参数来保存实际使用的类。每个类都是描述符的一个子类。
我假设我可以制作 R 对象的链接列表,但是当我尝试附加包含描述符子类的 R 类时,编译器会抱怨类型转换。
关于如何修复此编译错误的任何建议?
g++-4.7 -g -ggdb -DDEBUG=1 -Wall -std=c++11 -march=native -m64 -DINTEL -fno-strict-aliasing example.cpp -o example.x
example.cpp: In instantiation of ‘void n1::n2::R<D>::add() [with D = n1::n2::SubDescriptor2<int, int>]’:
example.cpp:68:14: required from here
example.cpp:37:10: error: cannot convert ‘n1::n2::R<n1::n2::SubDescriptor2<int, int> >* const’ to ‘n1::n2::R<n1::n2::Descriptor>*’ in assignment
example.cpp: In instantiation of ‘void n1::n2::R<D>::add() [with D = n1::n3::SubDescriptor<int, int>]’:
example.cpp:72:13: required from here
example.cpp:37:10: error: cannot convert ‘n1::n2::R<n1::n3::SubDescriptor<int, int> >* const’ to ‘n1::n2::R<n1::n2::Descriptor>*’ in assignment
工作示例:
#include <cstdint>
#include <utility>
#include <stdlib.h>
namespace n1 {
namespace n2 {
class Descriptor;
template<class D>
class R;
class Descriptor {
public:
int temp;
Descriptor() {}
Descriptor(int x) {
temp = x;
}
~Descriptor() {}
};
R<Descriptor> * list = nullptr;
template<class D>
class R {
public:
R<Descriptor> *pool_next;
D descriptor; //EDIT for some reason I only had d here...
template<typename... Args>
R(Args&&... args): descriptor(std::forward<Args>(args)...) {
};
void add() {
this->pool_next = list;
list = this;
}
};
template<class T, class W>
class SubDescriptor2: public Descriptor {
public:
SubDescriptor2(int x) {
temp = x;
};
~SubDescriptor2() {};
};
};
namespace n3{
template<class T, class W>
class SubDescriptor: public n2::Descriptor {
public:
SubDescriptor(int x) {
temp = x;
};
~SubDescriptor() {};
};
};
};
int main(int argc, const char * argv[]) {
n1::n2::R< n1::n2::SubDescriptor2<int, int> > *temp2;
temp2 = new n1::n2::R< n1::n2::SubDescriptor2<int, int> >(1);
temp2->add();
n1::n2::R< n1::n3::SubDescriptor<int, int> > *temp;
temp = new n1::n2::R< n1::n3::SubDescriptor<int, int> >(1);
temp->add();
return 1;
}
R<SubDescriptor>
不是R<Descriptor>
的子类。这是因为C++模板不是协变的。
我能想到的第一件事是将Descriptor*
保留在 R 类中,使用描述符作为其模板参数实例化所有 R,并在构建新 R 时传递描述符的不同子类。
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表