For quite a long time as was thinking about solution to my problem and I finally came to point when I have no other ideas but to ask here.
I have following problem.
Short version. How to inherit static field from base class, but make it unique in each derived class and keep possibility to upcast those classes to parent class?
Long version. I need to create some kind of basic interface for set of classes. Each of this classes need to have one static field and one static method. But I want to be able to pass all those classes as parameters to one universal function which uses those static members. So I was thinking about inheriting them all from one base class.
But of course I can't simply inherit static members and expect them to be unique in each child class. I was trying to use Curiously Recurring Template Pattern (CRTP), but it forces me to make this universal function template too and directly give it class name during each call. That's not good for me.
Also I have problems with making CRTP works when more than one level of inheritance is used (i.e. when I want to derive one more class from class derived from this template base class). Is there any way to achieve what I need?
I know that similar questions were already asked but in most of them authors were glad with CRTP. For me it doesn't seem like solution good enough.
//pseudo-code for what I need, doesn't work of course
class Base {
public:
static int x;
static int GetX() {return x;}
}
class Derived : public Base {};
class NextDerived : public Derived {};
class NextDerived2 : public Derived {};
void Foo(Base& a) {a.x = 10;}
int main {
NextDerived d;
NextDerived2 d2;
Foo(d);
Foo(d2); //both Foos modify different static variables
}
//CRTP attempt
template <class C>
class Base {
public:
static int x;
static int GetX() {return x}
};
class Derived : public Base<Derived> {};
int Derived::x = 0;
template <class C>
void Foo(Base<C>& b) {
b.x = 10;
return;
};
int main() {
Derived d;
Foo<Derived>(d);
}