I've got some widgets of different types. The widgets all have a method Update().
A top widget with member widgets needs to call all its members' Update() method in its UpdateMembers() method.
struct WidgetA{
void Update();
};
struct WidgetB{
void Update();
};
struct TopWidget{
WidgetA w1;
WidgetB w2;
//other widgets
void UpdateMembers(){
w1.Update();
w2.Update();
//other widgets
}
};
Manually updating UpdateMembers() when TopWidget's member list changes is error prone, so I need to do that automatically. The following code does the job, but it uses global states and has overhead in space and time. How can I do its job with some compile time programming?
#include <vector>
struct Updatable;
static std::vector<Updatable*> g_vec;
struct Updatable{
Updatable(){g_vec.push_back(this);}
virtual void Update()=0;
virtual ~Updatable();
};
struct WidgetA:Updatable{
void Update()override;
};
struct WidgetB:Updatable{
void Update()override;
};
struct TopWidget{
WidgetA wa;
WidgetB wb;
//other widgets
void UpdateMembers(){
for(auto w:g_vec){
w->Update();
}
}
~TopWidget(){
g_vec.clear();
}
};