How to find type of pointer - c++

I have a optional property event that I define as a pointer in this struct:
struct AnimatedSprite {
//...some other properties
Event *event;
};
Let's say I want to store a StartTransitionEvent , defined like this:
class Event {
public:
Event() = default;
};
class StartTransitionEvent: public Event {
public:
int test = 1;
};
I can create and assign the StartTransitionEvent:
auto sprite = AnimatedSprite{};
auto newEvent = StartTransitionEvent{};
sprite.event = &newEvent;
But how do I get the type once I need to call something like:
eventBus->EmitEvent<StartTransitionEvent>(sprite->event);
Should I do some sort of checking on my event pointer to get to the StartTransitionEvent? Or maybe not use pointers at all and go for a std::variant to store the event with all it's possible child-classes?

You could use double dispatch, a.k.a. visitor pattern and let the specific Event visit the EventBus.
So something like
class Event
{
public:
virtual void Emit(EventBus& eventBus) = 0;
};
class StartTransitionEvent : public Event
{
public:
void Emit(EventBus& eventBus) override
{
eventBus.EmitEvent(this);
}
};
sprite.event.Emit(eventBus);

Assuming you're designing such a hierarchy, your EventBus class should be able to work with the base Event class. You achieve that through virtual functions in the Event class:
struct Event {
Event() = default;
virtual ~Event() = default;
virtual void action1(); // event-specific actions
virtual void action2();
virtual void action3();
};
struct StartTransitionEvent : Event {
void action3() override; // override some actions
};
struct EventBus {
void emit(Event& event) {
// ...
event.action1();
// ...
event.action2();
// ...
event.action3();
}
};
int main() {
StartTransitionEvent event;
EventBus bus;
bus.emit(event);
}

Related

C++ Observer Mode, "does not name a type" compile error

I am writing an Arduino program where LEDs and a bunch of other electronics are controlled by different buttons. To simplify the code, I am using the Observer Mode:
class Observer observes EventThrowers, who performs check() every frame and notifies Observers if necessary. The code definition for Observer and EventThrower looks like this:
class Observer {
public:
virtual void handleEvent(int label, bool state) = 0; // Virtual method called by EventThrowers.
};
class EventThrower {
private:
std::vector<Observer *> observer_list;
protected:
void notifyObservers(int label, bool state) {
for (Observer *observer : observer_list) {
observer->handleEvent(label, state);
}
}
public:
virtual void check() = 0; // Virtual method used in loop() for frame checking.
void addObserver(Observer *_observer) {
this->observer_list.push_back(_observer);
}
};
And my LEDCtrl class (an Observer) and ButtonClick class (an EventThrower) definitions are:
class LEDCtrl : public Observer {
public:
// properties
LEDCtrl(int _led_pin) { ... } // constructor
void handleEvent(int label, bool state) { ... } // overridden handleEvent method
private:
void toggleLight(bool new_status) { ... } // assistant method
};
class ButtonClick : public EventThrower {
public:
// properties
ButtonClick(int _button_pin, int _default, int _label) { ... } // constructor
void check() { ... } // overridden check() that is called every frame to check the status of the button and choose to notify Observers or not
};
My initialization of a LEDCtrl-ButtonClick instance pair looks like:
ButtonClick *buttonClick1 = new ButtonClick(BUTTON1, 0, 0);
LEDCtrl *ledCtrl1 = new LEDCtrl(LED1);
buttonClick1->addObserver(ledCtrl1);
However, the above code throws this compile error:
error: 'buttonClick1' does not name a type
buttonClick1->addObserver(ledCtrl1);
^~~~~~~~~~~~
How can I fix this?

Decorator pattern: how can I call(back) some members of decorator wrappers from the core class

I am implementing a decorator pattern following the example in here:
Class I: is the interface class, common to both core class and decorator base class
Class A: is the core class
Class D: is the decorator base class
Classes X, Y, Z: inherit from the decorator base class and extend functionality of the core class dynamically
There is one method in class A (A::endTraining()), which is triggered at the end of a timer variable (also present in class A). This method needs to call some member of X, Y and Z classes.
Is it possible? Is it good practice? How?
For example, is creating a mechanism to register the pointers-to-XYZ::endTraining in class A a correct approach?
(showing only relevant bits)
typedef void (D::*pCallback_fn)(void);
class I
{
public:
virtual void endTraining() = 0;
virtual void regTrainingCallbacks(pCallback_fn ptrFn) = 0;
};
class A: public I {
public:
void endTraining() {
//do stuff
//then do stuff in D (and its derivatives)
// by iterating through fnList
}
void regTrainingCallbacks(pCallback_fn ptrFn)
{
fnList.push_back( ptrFn );
}
private:
std::list<pCallback_fn> fnList;
};
class D: public I {
public:
D(I *inner) {
m_wrappee = inner;
}
void regTrainingCallbacks(pCallback_fn ptrFn)
{
m_wrappee->regTrainingCallbacks(ptrFn);
}
private:
I *m_wrappee;
};
class X /*,Y,Z*/ : public D {
public:
X(I *core): D(core)
{
D::regTrainingCallbacks( this->*endTraining() ); //
}
private:
void endTraining(){
//do stuff when called by A::endTraining() through D
}
};
What can be done instead?
Addressing one fault in the original design, in which the 'trainer' (the entity registering training callbacks) must be a callback in itself (is there any reason the notifier - former class A - must be a callback itself?).
I changed the class names to put into evidence their responsibilities.
The MainTrainingProcess replaces the original class A (instances of which would have been wrapped by D-es) and the D itself.
class EndTrainingListener
{
public:
virtual ~EndTrainingListener() { }
virtual void endTraining()=0;
};
class ITrainingProcess
{
public:
virtual ~ITrainingProcess() { }
virtual void regTrainingCallbacks(EndTrainingListener* callback) = 0;
};
class MainTrainingProcess : public ITrainingProcess {
public:
virtual ~MainTrainingProcess() {
// destroy other resources used during training
}
virtual void regTrainingCallbacks(EndTrainingListener* callback) {
this->listeners.push_back(callback);
}
void train() {
// do training stuff
// ...
// do my specific actions at the end of training
// ...
// finish by notifying all listeners
this->atEndTraining();
}
protected:
void atEndTraining() {
for(auto l : this->listeners) {
l->endTraining();
}
}
std::list<EndTrainingListener*> listeners;
};
class X /*Y, Z*/ : public EndTrainingListener {
public:
virtual ~X();
virtual void endTraining() {
// do specific stuff
}
};

How to refer overriden static method from parent class constructor?

So we have some class (i.e. Button) and its method which takes void function.
Also we have parent class State which has static method buttonAction used to asign
to Button instance. Problem is State's child class must have an option to override
static method buttonAction and this method must be assigned to button by parent class State constructor.
It must work something like this:
Code:
MyState st;
button.click();
Desired output:
MyState::buttonAction!
But instead I get:
State::buttonAction!
Related .cpp file:
#include <iostream>
#include <cstdio>
class Button
{
public:
void setAction(void(*foo)(void));
void click();
private:
void(*foo)(void);
};
void Button::setAction(void(*foo)(void)) { this->foo = foo; }
void Button::click() { this->foo(); }
Button button;
class State
{
public:
State();
private:
static void buttonAction();
};
State::State()
{
button.setAction(this->buttonAction); // pointer to state's buttonAction
}
void State::buttonAction()
{
printf("State::buttonAction!");
};
class MyState : State
{
private:
static void buttonAction(); // overridden buttonAction
};
void MyState::buttonAction()
{
printf("MyState::buttonAction!");
};
int main() {
MyState st;
button.click();
return 0;
}
Have MyState's constructor override it:
MyState::MyState()
{
button.setAction(&buttonAction)l
}
After the superclass initially invokes setAction() to point the callback to its own static class function, this will override it, and repoint it to MyState's static class function.

A list with the same type as the class it's contained within

I'm trying to create a simple events system, which will have many different events. So, I've tried to create an event class which allows you to register functions, taking the correct type of event, and returning a boolean.
What I want is that the method post in any subclass of Event will take that subclass rather than Event, and the functions in the list listeners in each subclass should take the correct subclass type. Here's the code I already have, which forces the function to cast to the correct event type:
events.h:
namespace events {
class Event {
public:
static const std::List<bool (*)(Event)> listeners;
void post(Event event);
}
class ExampleEvent : Event {
int eventData;
}
}
events.cpp:
namespace events {
void Event::post(Event event) {
for(int i = 0; i < listeners.size(); i++) {
if(listeners[i](event)) return;
}
}
}
Is there some way I can get this to work with subclassed events without having to do the following?
bool handleExample(Event event) {
ExampleEvent exampleEvent = (ExampleEvent)event;
std::cout << exampleEvent.eventData << std::endl;
return false;
}
// Somewhere else in the code
ExampleEvent::listeners.push_back(&handleExample);
I apologise for any incorrect code, I don't quite have the rules of the language perfect yet.
The common way is to use CRTP:
namespace events {
template<typename Derived>
class Event {
public:
static const std::list<bool (*)(Derived)> listeners;
void post(Derived event)
{
static_cast<Derived&>(*this).post(event);
}
};
class ExampleEvent : Event<ExampleEvent> {
int eventData;
void post(ExampleEvent event)
{
//implement post
}
};
}
Just use virtual functions:
namespace events {
class EventHandler {
public:
static const std::list<Event*> listeners;
void post() {
for (Event * listener : listeners) {
if (listener->post()) break;
}
}
};
class BaseEvent {
public:
virtual bool post() = 0;
virtual ~BaseEvent() {}
};
class ExampleEvent : public BaseEvent { // use public inheritance
int eventData;
public:
virtual bool post() override {
if (eventData == 0) return true;
return false;
}
};
}

C++ - Polymorphic pointer to member functions

I'm not very good at C++ (but I'm familiar with OOP/Java), but I have to create a game for my C++ class. I want to setup a kind of game engine like that used for Flash games written in ActionScript.
I wrote this two classes, where Actor is meant as a base class (probably will be abstract) and Player should actually implement it.
The problem is that I want to avoid duplicate code in the functions addEventListener and handle and re-declaring _handlerMap, since I want to achieve data hiding and such things.
The problem, I guess, is that _eventMap should contain handler values that can change class Actor::*handler and Player::*handler. Is it possible?
class Actor {
protected:
typedef void(Actor::*handler)(Event);
map<int, handler> _handlerMap;
public:
virtual void addEventListener(int ID, handler h) {
_handlerMap.insert(std::make_pair(ID, h));
};
virtual void handle(int ID) {
handler h = _handlerMap[ID];
Event e;
if (h)
(this->*h)(e);
}
virtual void onUpdate(Event e) {
cout << "Actor::onUpdate()" << endl;
};
};
class Player : public Actor {
typedef void(Player::*handler)(Event);
map<int, handler> _handlerMap;
public:
void addEventListener(int ID, handler h) {
_handlerMap.insert(std::make_pair(ID, h));
};
void handle(int ID) {
handler h = _handlerMap[ID];
Event e;
if (h)
(this->*h)(e);
}
void onKeydown(Event e) {
cout << "Player::onKeyDown()" << endl;
};
};
I wish it was possible to declare Player as:
class Player : public Actor {
typedef void(Player::*handler)(Event);
public:
void onWhateverEvent(Event e);
}
I hope you understand.
You need something like this (not tested):
class Dispatcher {
public:
virtual void dispatchEvent(Event*) = 0;
};
template <class C>
class DispatcherImpl : public Dispatcher
{
typedef void(C::*handler)(Event* e);
std::map<int, handler> _handlerMap;
C* _owner;
public:
DispatcherImpl (C* c) : _owner(c) {}
addEventListener(int ID, handler h) {
_handlerMap.insert(std::make_pair(ID, h));
}
void dispatchEvent(Event*)
{
handler h = handlerMap[e->id];
if (h) (_owner->*h)(e);
}
}
Now let each type T of actor own a DispatcherImpl<T>, and you are all set. You may also have e.g. Player inherit from DispatcherImpl<Player>.
What do you think of this? (Dispatcher is the same as DispatcherImpl above)
template <class T>
class Entity {
T *_instance;
Dispatcher<T> *_dispatcher;
public:
Entity() {
_instance = new T();
_dispatcher = new Dispatcher<T>(_instance);
}
};
class Actor {
//attirbutes and methods
};
class Player : public Actor {
//attirbutes and methods
};
To use it just:
Entity<Actor> *actor = new Entity<Actor>();
Entity<Player> *player = new Entity<Player>();
actor->getDispatcher()->addEventListener(0, &Actor::foo);
player->getDispatcher()->addEventListener(1, &Player::bar);
player->getDispatcher()->addEventListener(0, &Actor::foo); //inheritance