Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance static variable member, but share it separately to every kind of the inheritance class

If class inherits base class with static variable member, Will be their only one member that shared with all classes that inheritances.

I have few kinds inherits classes, and many instance of every one of them. I want that every one of the inherits classes will have a separate static member, that shared with all of its instances.

How can it be done?

thank you, and sorry about my poor English.

edit:

class a{
static int var;};
class b::a{};
class c::a{};

Now, I want that all instances of b will have same var, and all instances of c will have same var , but the var of b will be different from the var of c.

I'm sorry again about my English, if you can correct me, please do it.

like image 242
yoni Avatar asked Dec 17 '22 06:12

yoni


1 Answers

You can work aroud that using CRTP :

struct YourBaseBaseClass {
    // put everything that does not depend on your static variable
};

template <YourSubclass>
struct YourBaseClass : YourBaseBaseClass {
    static Member variable;
    // and everything that depend on that static variable.
};

struct AClass : YourBaseClass<AClass> {
     // there is a "variable" static variable here
};

struct AnotherClass : YourBaseClass<AnotherClass> {
     // which is different from the "variable" static variable here.
};

AClass and AnotherClass both have a variable static variable (of type Member), but the first one is a static variable from YourBaseClass<AClass> and the other is from YourBaseClass<AnotherClass>, which are two different classes.

YourBaseBaseClass is optional, but you need it if you want to manipulate AClass and AnotherClass using a YourBaseBaseClass* pointer (you cannot have a YourBaseClass* pointer, because YourBaseClass is not a class).

And remember to define those static variables.

like image 151
BatchyX Avatar answered Feb 15 '23 23:02

BatchyX