How to use std::auto_ptr to achieve covariance assignment?

149 views Asked by At

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<> >.

1

There are 1 answers

0
Juraj Blaho On BEST ANSWER

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.