[英]How can I write generic code that will be inherited?
我正在尝试在继承的父 class 中编写一些通用代码。 但是,我正在努力输入一些变量。 拿下面的代码:
class A {
protected:
std::vector<void*> struct1;
std::vector<void*> struct2;
std::vector<void*> struct3;
public:
A::~A()
{
for(decltype(A::struct1)* i : A::struct1) {
free(i);
}
for(decltype(A::struct2)* i : A::struct2) {
free(i);
}
for(decltype(A::struct3)* i : A::struct3) {
free(i);
}
}
}
class B {
protected:
std::vector<b*> struct1;
std::vector<b*> struct2;
std::vector<b*> struct3;
}
class C {
protected:
std::vector<c*> struct1;
std::vector<c*> struct2;
std::vector<c*> struct3;
}
(其中b
和c
是结构)。
我遇到了迭代器的问题( a value of type "void *" cannot be used to initialize an entity of type "std::vector<void *, std::allocator<void *>> *"
),这使得感觉。 但是 class 永远不会直接使用 A,只有 B 和 C,所以 A 永远不会遇到这个问题,因为结构将具有正确的类型。
您的意思是您希望像B
这样的类从A
继承,以便析构函数破坏vector
s 的内容吗?
template<typename T>
class A {
protected:
std::vector<T*> struct1;
std::vector<T*> struct2;
std::vector<T*> struct3;
public:
A::~A() {
for(auto i : struct1) {
delete i;
}
for(auto i : struct2) {
delete i;
}
for(auto i : struct3) {
delete i;
}
}
}
class B: public A<B> {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.