I have base class and a bunch of derived classes (only one here for simplicity). I also have holder class with one of derived classes as a template argument. I want holder object to create an instance of derived class. Here is the code:
class base {
protected:
int value;
public:
base() : value (0) { }
base(int value) : value(value) { }
};
class derived : public base { };
template <class T>
class holder {
public:
holder(T) {}
T create(int value) {
return T(value);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
holder<base*> h(&derived());
derived* d = h.create(1); // error here
}
I get an error error C2440: 'initializing' : cannot convert from 'base *' to 'derived *'. I guess that's because type of variable is holder<base*>, so create method is called with base as template argument. But how do I cast it properly if I have a lot of derived classes?
UPD.
I changed holder::create method so it uses std::remove_pointer but I still get the same compile error.
T create(int value) {
return new (std::remove_pointer<T>::type)(value);
}
base*with anint? Does your code compile ?