Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top