简体   繁体   中英

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. 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).

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. 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.

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?

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> {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM