I have the following code that doesn't compile.
class Base {
public:
virtual ~Base() { };
};
class Derived : public Base { };
class NotDerived { };
template <typename T>
class Group { };
int main() {
Group<Base> *g = NULL;
g = new Group<Base>(); // Works
g = new Group<Derived>(); // Error, but I want it to work
g = new Group<NotDerived>(); // Error, as expected
}
I understand that this won't compile because g
is a different type than Group<Derived>
. To make this work in Java I would do something such as Group<? extends Base> g
, but C++ doesn't have that keyword as far as I know. What can be done?
Edit: I would like to clarify that I do not want it possible to set types not derived from Base
as g
. I have updated my example to explain this.
Edit 2: There are two solutions to my problem. Dave's I found to be simple and easy to define. But Bowie's (along with Mark's additions) suited my needs better.