Reputation: 14309
I have the following use case but I can't figure out how to make it work:
enum MyTemplateEnum { A, B };
template<MyTemplateEnum T = A>
class MyTemplateClass<T> {
// ...
};
std::string argument = ...;
std::auto_ptr<MyTemplateClass<> > instance;
if (argument == "a") {
std::auto_ptr<MyTemplateClass<A> > temp(new MyTemplateClass<A>(...));
instance = temp;
} else
if (argument == "b") {
std::auto_ptr<MyTemplateClass<B> > temp(new MyTemplateClass<B>(...));
instance = temp;
}
this results in compilation error because I basically can't assign a concrete realization std::auto_ptr<MyTemplateClass<A> >
to a generic version std::auto_ptr<MyTemplateClass<> >
.
Upvotes: 3
Views: 149
Reputation: 13451
You need a common base class for all instantiations of the MyTemplateClass<T>
template. Otherwise all the instatiations are unrelated classes.
class MyTemplateBase {
public:
// Don't forget virtual destructor.
virtual ~MyTemplateBase() {}
};
template<typename T = A>
class MyTemplateClass : public MyTemplateBase {
};
std::auto_ptr<MyTemplateBase> instance;
if (argument == "a") {
instance.reset(new MyTemplateClass<A>(...));
} else if (argument == "b") {
instance.reset(new MyTemplateClass<B>(...));
}
Note that std::auto_ptr
is obsolete. If possible use std::unique_ptr
or boost::scoped_ptr
instead.
Upvotes: 2