Reputation: 753
So I don't know if this is possible but I've got a setup that looks a little something like:
template <class T>
struct Something;
struct Example {
//not sure how this should be defined
//I was thinking void*, but I can't use pointers as the 'Something' class moves around the instances
//and I don't want to have to constantly update the pointers.
std::vector<?> addedTypes;
template<typename T>
void addThing() {
addedTypes.push_back(T);
Something<T>::addThing(*this);
}
void destroy() {
for (auto T : addedTypes) {
Something<T>::removeThing(*this);
}
}
};
template <class T>
struct Something {
static void addThing(Example e) {/*...*/}
static void removeThing(Example e) {/*...*/}
};
Basically I want to know how I could go about making a list of types that have been added to loop so later I can call the static remove function?
Edit: Adding a little more info as suggested by the comments.
This is just for example, its actually an entity component system where "Example" is an entity, and "Something" is a CRTP component. All the logic is stored in the components, aside from an ID and some helper functions in the entity. The only part missing is a way to destroy the components (of various types) from the entity (i can do this already from the components, but without having the types, I'm not sure how to go about this from the entity.
As for the reason static functions are being called in the "Something" class, they interact with other static class members (e.g. std::vector<T> list
), and do not touch instanced member state.
Upvotes: 3
Views: 1821
Reputation: 217065
It is not building list of type, but provide a list of "remover".
I use std::function
here, maybe create IRemover
would make more sense for you (or simple function pointer is enough):
template <class T>
struct Something;
struct Example {
std::vector<std::function<void(Example&)>> removers;
template<typename T>
void addThing() {
removers.push_back(&Something<T>::removeThing);
Something<T>::addThing(*this);
}
void destroy() {
for (auto& f : removers) {
f(*this);
}
removers.clear();
}
};
Upvotes: 6