문제

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top