[英]How can I write generic code that will be inherited?
I'm trying to write some generic code in a parent class that gets inherited.我正在尝试在继承的父 class 中编写一些通用代码。 However, I'm struggling with the type-ing of some of the variables.
但是,我正在努力输入一些变量。 Take the code below:
拿下面的代码:
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;
}
(where b
and c
are structs). (其中
b
和c
是结构)。
I'm getting issues with the iterator ( a value of type "void *" cannot be used to initialize an entity of type "std::vector<void *, std::allocator<void *>> *"
), which makes sense.我遇到了迭代器的问题(
a value of type "void *" cannot be used to initialize an entity of type "std::vector<void *, std::allocator<void *>> *"
),这使得感觉。 But class A will never be directly used, only B and C, so A won't run into that issue ever because the structs will have proper types.但是 class 永远不会直接使用 A,只有 B 和 C,所以 A 永远不会遇到这个问题,因为结构将具有正确的类型。
Did you mean that you wanted classes like B
to inherit from A
so that the destructor will destroy the contents of the vector
s?您的意思是您希望像
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.