My question is: Is there a way to declare static member pointers to their own classes automatically?
I have a C state machine, in which classes have static pointers to their own classes. This means I can bind a given object to the pointer in its class uniquely. In other words, from each class, only 1 instance can be bound to the static pointers, which pointers then can be used to select from the pool of instances the one that is currently bound.
class A {
public:
static A *ptr;
void bind() { ptr = this; }
}
class B {
public:
static B *ptr;
void bind() { ptr = this; }
}
To me this seems like there has to be some way to abstract this. The process in each class is basically the same: a static pointer to the class and a bind function to assign this
to said pointer. (I'm aware of the dangers regarding the lifetimes of each particular bound object, consider this taken care of.)
As far as I know, these type of abstractions are usually performed with inheritance, however I can't seem to find a way to abstract out the type of ptr
in a hierarchy, or using template classes.
The optimal solution would be one that doesn't need any information from the programmer regarding the type of ptr
in any of the classes, since it seems to be available information at compile time.
Can this be done? Can it be avoided to explicitly declare ptr
in each class and automate the process?
This is the closes I got to a solution, but did not succeed: C - Are there ways to get current class type with invariant syntax?
Thank you in advance!
CodePudding user response:
The only thing I can think of would be a CRTP-based approach, something like:
template<typename T> struct current_instance {
static T *ptr;
void bind() { ptr = static_cast<T *>(this); }
};
// ...
template<typename T> T *current_instance<T>::ptr;
//--------------------------------------------------------------
class A : current_instance<A> {
// ...
};
class B : current_instance<B> {
// ...
};