I have a class named MyClass
that is subscribed by another class. When some events happen, MyClass
should notify subscribers.
I'm trying to use template for the subscriber's type. Because I don't want to let others(who are in charge of subscriber class) need to care about modifying MyClass
for subscribing.
So I've written codes below,
class MyClass {
public:
template<typename T>
void subscribeEvents(const T &controller)
{
m_subscriber = static_cast<T*>(m_subscriber);
m_subscriber = &controller;
}
void notifyPositionChanged(const long &position) const {
(m_subscriber)->onPositionChanged(position);
}
private:
void m_subscriber; // will be changed to array or something else
}
Actually the controller
object has a method namedonPositionChanged
.
But as you know, it's not compiled for this line.
(m_subscriber)->onPositionChanged(position);
Now I understand why it's an error, but the problem is that I don't know how to modify codes or change my design. Please let me know what I'm missing and misunderstanding. Thanks in advance.
You dont need to use template for this. Just use a base class for your subscribers. And MyClass operate on your base class
class ISubscribe {
public:
virtual void onPositionChanged(const long &position) = 0;
};
class MyClass {
public:
void subscribeEvents(ISubscribe *controller)
{
m_subscriber = controller;
}
void notifyPositionChanged(const long &position) const {
(m_subscriber)->onPositionChanged(position);
}
private:
ISubscribe *m_subscriber; // will be changed to array or something else
};
class SampleSubscriber : public ISubscribe {
public :
void onPositionChanged(const long &position) override{
...
}
};
void main() {
SampleSubscriber s;
MyClass m;
m.subscribeEvents(&s);
....
}