I'm working on implementing an observer design pattern with a notification
object that I can change to suit various observed classes.
Here is the observer framework:
notify.h:
class INotification //Notification container
{
public:
virtual ~INotification()=0;
};
inline INotification::~INotification() {}
class IObserver
{
public:
virtual ~IObserver();
virtual void update(INotification*)=0;
};
inline IObserver::~IObserver() {}
class ISubject
{
public:
virtual ~ISubject();
virtual void attach(IObserver*)=0;
virtual void detach(IObserver*)=0;
virtual void notify()=0; //Note: observer deletes notifications
};
inline ISubject::~ISubject() {}
I am implementing a timer class that I want other classes to observe for timer events:
timer.h:
class ITimerObserver;
class ITimer : public ISubject
{
public:
virtual ~ITimer();
virtual void setInterval(const unsigned int,const unsigned int)=0; //Seconds, Microseconds
virtual void run()=0; //Check for triggering
virtual const timeval& now()=0;
virtual bool isItTime(const timeval&,const timeval&)=0;
};
inline ITimer::~ITimer() {}
class CTimer : public ITimer
{
protected:
std::vector<IObserver*> observers;
timeval interval; //How often we are triggering
timeval lastTrigger; //When we were last triggered
timeval current; //Our current time
private:
virtual ~CTimer();
virtual void attach(IObserver*);
virtual void detach(IObserver*);
virtual void notify();
virtual void setInterval(const unsigned int,const unsigned int); //Seconds, Microseconds
virtual void run(); //Check for triggering
virtual const timeval& now();
virtual bool isItTime(const timeval&,const timeval&);
};
class ITimerNotification : public INotification
{
public:
virtual ~ITimerNotification();
virtual const timeval& getTime()=0;
};
inline ITimerNotification::~ITimerNotification() {}
class CTimerNotification : public ITimerNotification
{
public:
CTimerNotification(const timeval& t)
{
time = t;
}
protected:
timeval time;
private:
virtual ~CTimerNotification();
virtual const timeval& getTime()
{
return time;
}
};
class ITimerObserver : public IObserver
{
public:
virtual void update(ITimerNotification*)=0;
};
So I want to be able to pass a more specific Notification object (A TimerNotification) whenever a timer event happens, so that I can call a specific update() function on the observer, so I made a new Observer class (ITimerObserver).
Here is the function that notifies the observer on a timer event:
void CTimer::notify()
{
std::vector<IObserver*>::iterator it;
for(it=observers.begin();it!=observers.end();++it)
{
ITimerNotification* notification = new CTimerNotification(now());
(*it)->update(notification);
}
}
Here is the actual observer itself:
class TestObserver : public ITimerObserver
{
public:
virtual void update(INotification* note)
{
std::cout<<"???: TestObserver: update()!\n";
}
virtual void update(ITimerNotification* note)
{
std::cout<< note->getTime().tv_sec << "." << note->getTime().tv_usec <<": TestObserver: update()!\n";
}
};
When run, the program runs the interface method, void update(INotification) instead of the more specific ITimerNotification as I would expect. The trouble is, how do I get the CTimer class to know about the TimerObserver without breaking the interface contract that says it only takes a Base Observer pointer?
To answer the first part of the question:
ITimerNotification* notification = new CTimerNotification(now());
(*it)->update(notification);
This code passes notification to an IObserver::update method, of which there is only one:
virtual void update(INotification*)=0;
Hence the call to that virtual method in TestObserver.
For the second part, you need to recognise that you wish the call to in a sense be virtual on two types, the observer and notification. This is known as double dispatch, and requires some work in C++.
The key point to understand is the static and run-time binding of the function calls. At the calling point, for example:
(*it)->update(notification);
the compiler can only do static resolution of the names of functions. Where these are virtual calls, there will be run-time binding to the actual method based on the type of object the method is being called on (not the parameter). So in order to do double dispatch through built-in mechanisms, you need to call a virtual method on both the notification and the observer.
See for example:
Multiple dispatch in C++
How does double dispatch work in Visitor pattern?
This topic is also covered in great detail in one of the Meyer's books (I forget which.)
Related
This question already has answers here:
Inherit interfaces which share a method name
(5 answers)
Closed 5 years ago.
I have the following code using multiple inheritance. The purpose is to use two interfaces as one in the derived class:
struct InterfaceA
{
virtual void register_stuff();
virtual void on_state_changed( const State state ) = 0;
};
struct InterfaceB
{
virtual void register_stuff();
virtual void on_state_changed( const State state ) = 0;
};
struct Derived : InterfaceA, InterfaceB
{
void register_stuff() override
{
InterfaceA::register_stuff();
InterfaceB::register_stuff();
}
void on_state_changed( const State state ) override
{
// how can I know who is responding?
}
};
Registering the interfaces will cause an asynchronous call to on_state_changed. Is it possible to discern which interface is calling it?
You'll have to add a layer in-between to disambiguate. Here's a small utility that creates those on the fly:
template<class Inteface>
struct disambiguate : Interface {
void on_state_changed( const State state ) override final {
on_state_changed(state, this);
}
virtual void on_state_changed( const State &state, disambiguate* ) = 0;
};
And that's it. Then it's a matter of defining your class in terms of this utility:
struct Derived : disambiguate<InterfaceA>, disambiguate<InterfaceB>
{
void register_stuff() override
{
InterfaceA::register_stuff();
InterfaceB::register_stuff();
}
void on_state_changed( const State &state, disambiguate<InterfaceA>* ) override
{
// Called for A
}
void on_state_changed( const State &state, disambiguate<InterfaceB>* ) override
{
// Called for B
}
};
I've used another parameter and overloading to make this templatized, but the technique itself can also be done by writing the classes out and calling a virtual function with a new name. The key is to make the original virtual call (via the interface pointer) reach a short thunk that calls the disambiguated function.
Alternatively it is possible to provide separate implementations for handlers directly in the code of Derived:
struct Derived : InterfaceA, InterfaceB
{
void register_stuff() override
{
InterfaceA::register_stuff();
InterfaceB::register_stuff();
}
void InterfaceA::on_state_changed( const State state ) override
{
// responding A
}
void InterfaceB::on_state_changed( const State state ) override
{
// responding B
}
};
EDIT: Unfortunately this solution is nonstandard and supported only by Visual C++ compilers.
I was thinking about using templates for disambiguating too, but I belive #StoryTeller 's answer is more elegant.
struct InterfaceA
{
virtual void register_stuff(); // calls on_state_changed<InterfaceA>()
template <typename Interface>
virtual void on_state_changed( const State state ) = 0;
};
struct InterfaceB
{
virtual void register_stuff(); // calls on_state_changed<InterfaceB>()
template <typename Interface>
virtual void on_state_changed( const State state ) = 0;
};
struct Derived : InterfaceA, InterfaceB
{
void register_stuff() override
{
InterfaceA::register_stuff();
InterfaceB::register_stuff();
}
template <typename Interface>
void on_state_changed( const State state ) override
{
// how can I know who is responding?
// : "Interface" is responding
}
};
The content
The question
Example
Why do I need it
Hi.
The question
I am facing a problem. I have a class A that has a base B (is polymorphic). In B class is method Print(), wich is virtual. In A class is also Print(). virtual.
Lets say I am given an A type object (or pointer), stored in B variable
B * object = new A();
And by calling
object->Print();
It calls the method in A class, but I also want it to call method in B class.
Technically
I want to call the method for each child until i reach class that has no child
This can be done as follows:
Example
class A
{
public:
virtual void Print() const override
{
cout << "A" << endl;
}
};
class B : public A
{
public:
virtual void Print() const override
{
cout << "B" << endl;
A::Print(); // i do not want to call it here...
}
};
The problem is that I do want not to be forced to call the
A::Print();
Why
Yes, you might be asking, what is the deal...
I have very long inheritance chain. (lets say that there are like 15 - 20 classes in the inheritance chain).
In a game, each one does some little thing.
Lets say
class GameObject
{
public:
virtual void Update() const
{
//updates position, recounts it towards screen
}
};
class Character : public GameObject
{
public:
virtual void Update() const override
{
// Updates lives, movement
}
};
class Warrior : public Character
{
public:
virtual void Update() const override
{
// Updates armor, specific stuff
}
};
Now this example is very simplified. Problem is, that if i forget to add a call base::Update() Then I am worndering why does it not work. Looking for such a misstake is hard. I mean, if there any way around it?
Thank you very much indeed for any responses.
Have a nice day
If indeed every class must call the base function, one way to ensure the functionality is enforced is to use the template pattern.
class GameObject
{
public:
void Updater()
{
Update(); // this is a virtual call
GameObject::Update(); // now call base
}
virtual void Update() const
{
}
};
class Character : public GameObject
{
public:
virtual void Update() const override
{
// Updates lives, movement
}
};
class Warrior : public Character
{
public:
virtual void Update() const override
{
// Updates armor, specific stuff
}
};
class Character : public GameObject
{
public:
virtual void Update() const override
{
// Updates lives, movement
}
};
class Warrior : public Character
{
public:
virtual void Update() const override
{
// Updates armor, specific stuff
}
};
Then always call YourObject::Updater(); instead of YourObject::Update(). The Updater function will call your object's Update function, and then return and call the base class Update.
There was once a proposal to get all the bases of a given type (N2965) which gcc actually implemented in <tr2/type_traits>. So, if portability is not a concern and you happen to be using gcc, you can write a catch-all like so:
struct A {
virtual ~A() = default;
virtual void print() { print_all(*this); }
void print_one() { std::cout << "A\n"; }
protected:
template <class T>
void print_all(T& object) {
object.print_one();
print_all(object, typename std::tr2::bases<T>::type{});
}
template <class T, class... Bases>
void print_all(T& object, std::tr2::__reflection_typelist<Bases...> ) {
using swallow = int[];
(void)swallow{0,
(static_cast<Bases&>(object).print_one(), 0)...
};
}
};
This splits up print(), which prints everything, and print_one() which just prints the one specific type. You just have your print() call print_all() with itself:
struct B : A {
void print() override { print_all(*this); }
void print_one() { std::cout << "B\n"; }
};
struct C : B {
void print() override { print_all(*this); }
void print_one() { std::cout << "C\n"; }
};
Otherwise, you'll have to wait for one of the reflection proposals to get adopted.
I am looking for an elegant solution for my case. I tried to find a design pattern that specified and offers solution for this case but i failed to find one.
I have a base class that uses to store general object and later Invoke it.
I want the execution will be separated into two parts:
A must have part which will always take place (do1st()).
User defined code (do2nd()).
For example:
class InvokeBase
{
public:
InvokeBase(void *ptr) : context_(ptr) {}
virtual ~InvokeBase () {}
void operator()() = 0;
protected:
void do1st() {//Mandatory code to execute for every InvokeBase type when calling operator()};
void * context_;
};
class InvokeDerived : public InvokeBase
{
public:
InvokeDerived(void *ptr) : base(ptr){}
virtual ~InvokeDerived();
void do2nd() {//User defined code}
void operator()()
{
do1st(); // << How to force this execution?
do2nd();
}
};
void main()
{
InvokeBase *t = new InvokeDerived();
t(); // << here i want the execution order will be do1st and then do2nd.
}
The trick is that i want do1st will execute always, that i will not have to call it from InvokeDerived. I want to allow the user to inherit from InvokeBase with the guarantee that do1st will always be called when invoking the operator().
This is the template method pattern: split a function with semi-flexible behavior accross the class hierarchy into multiple parts, and make virtual only the ones that change:
class InvokeBase
{
public:
InvokeBase(void *ptr) : context_(ptr) {}
virtual ~InvokeBase () {}
void operator()() // this is non-virtual (this is the template method)
{
do1st();
do2nd(); // this resolves to virtual call
}
protected:
void do1st() { /* fixed code here */ };
virtual void do2nd() = 0; // variable part here
void * context_;
};
class InvokeDerived : public InvokeBase
{
public:
InvokeDerived(void *ptr) : base(ptr){}
virtual ~InvokeDerived() = default;
protected:
void do2nd() override
{
// code speciffic to InvokeDerived here
}
};
I've created a class named 'Device' which get inherited by multiple devices (for example, RFDevice, AccelleroDevice)
The Device class inherited a Thread class. This Threadclass includes a Pure virtual function named run. Is it possible to accesss this pure virtual function in RFDevice or AcelleroDevice.
So,
ThreadClass->DeviceClass->RFDeviceClass.
I've tried to add
' virtual void run(void) = 0' also in the device class but this wont work.
Greets,
Only if the virtual function is not private. If it is, then you cannot call it and are not supposed to, either:
class ThreadClass
{
public:
virtual ~ThreadClass() {}
private:
virtual void run() = 0;
};
class Device : public ThreadClass
{
};
class RFDevice : public Device
{
public:
void f()
{
run(); // compiler error
}
};
If it is protected or public, then it will work, provided there is an implementation of the function somewhere down the class hierarchy. But with the exception of the destructor, virtual functions should rarely be public or protected in C++:
class ThreadClass
{
public:
virtual ~ThreadClass() {}
protected:
virtual void run() = 0; // non-private virtual, strange
};
class Device : public ThreadClass
{
};
class RFDevice : public Device
{
protected:
virtual void run()
{
}
public:
void f()
{
run(); // works
}
};
Of course, this does not technically call the base function. And that's a good thing; you'd end up with a pure virtual function call otherwise, and your program would crash.
Perhaps what you need to do is to just implement the private virtual function. That would be the preferred class design:
class ThreadClass
{
public:
virtual ~ThreadClass() {}
void execute()
{
run();
}
private:
virtual void run() = 0;
};
class Device : public ThreadClass
{
};
class RFDevice : public Device
{
private:
virtual void run()
{
}
};
int main()
{
RFDevice d;
d.execute();
}
If you are not just maintaining a legacy code base, you should probably get rid of your thread class and use C++11 multi-threading.
I have a base class and classes that derive from it. The base class Controllable acts as an interface for an input loop, and other classes derive from it to get a spot in that loop to get events like if a key is pressed.
class Controllable{
public:
virtual void setActive(bool state) { m_active = state; }
virtual void input(Event & e) =0;
private:
bool m_active;
};
class Button : public Controllable{
public:
void setActive(bool state){ /*do extra work*/ m_active = state; }
void input(Event & e) override;
};
Since the Button class deals with events from an event queue, setting it to inactive (which takes it out of the input loop) may cause it to miss important events like a key being unpressed, so it needs extra code to put it into a friendly inactive state should it ever become active again later.
My question, what is the best way to ensure that setActive always has the intended effect of switching m_active to the correct state, while at the same time, not requiring derived classes to define it unless they need to attach extra needed code?
Keep the setActive method non-virtual and then define a separate protected method activeChanged that the child classes can override
class Controllable{
public:
void setActive(bool state) { m_active = state; activeChanged(state); }
virtual void input(Event & e) = 0;
protected:
virtual void activeChanged(bool newState) {}
private:
bool m_active;
}
class Button : public Controllable{
protected:
void activeChanged(bool newState){ /*do extra work*/ }
public:
void input(Event & e);
};
With this approach you are keeping the external public interface separated from the internal protected interface intended for child classes.
One way to do this is to define "pre" and "post" virtual methods:
class Controllable{
public:
void setActive(bool state) {
preSetActive(m_active, state);
m_active = state;
postSetActive(m_active);
};
virtual void input(Event & e) =0;
protected:
virtual void preSetActive(bool oldState, bool newState) {}
virtual void postSetActive(bool newState) {}
private:
bool m_active;
}
Note that the setActive() method is not virtual in this technique.
Basically your case is custom made for Template method design pattern.
How about making setActive() non-virtual but instead adding a second virtual member (e.g. onSetActive())that's called by setActive()?
My 2 cents:
split your behaviour between 2 tasks:
virtual doActive(){}; //doNothing
void setActive (bool state) {
m_active = state;
doActive();
}