Reputation: 8145
I'm trying to create some kind of callback for a class template. The code is like this:
template <typename t>
class Foo {
void add(T *t) {
prinf('do some template stuff');
on_added(t);
}
void on_added(T *t) { }
}
struct aaa {}
class Bar : Foo<aaa> {
void on_added(aaa *object) {
printf("on added called on Bar");
}
}
the on_added function on Bar never gets called. What would be the best way to add a callback that a template subclass could optionally override? Thanks
Upvotes: 2
Views: 185
Reputation: 1903
Everyone else has already answered the question. Let me just add that adding virtual functions breaks backward compatibility of the class. So, if this is a class that you control and there are no other dependent classes, then yes you can go ahead and convert the on_added
to virtual, if not you need to make sure that the dependent modules are also rebuilt.
Upvotes: 0
Reputation: 24988
Use 'virtual'...
template <typename t>
class Foo {
void add(T *t) {
prinf('do some template stuff');
on_added(t);
}
virtual void on_added(T *t) { }
}
struct aaa {}
class Bar : Foo<aaa> {
void on_added(aaa *object) {
printf("on added called on Bar");
}
}
Upvotes: 4
Reputation: 229563
You have to make the function virtual
if you want calls in the base class to use the implementation in the derived class:
template <typename t>
class Foo {
...
virtual void on_added(T *t) { }
};
Note that this is not special to templates, but applies to all classes.
Upvotes: 0