Factories and conversion from Base to Derived...
Hi all,
I want to know whether the following is possible. I started out
with an idea called a CreationAbstractor. Basically just a
factory function wrapper for all types.
It looks like this:
template <class T>
class CreationAbstractor
{
public:
virtual T* create() const = 0;
virtual ~CreationAbstractor(){ }
protected:
CreationAbstractor(){ }
};
Typically, it would be used as argument to a class constructor like
this:
Driver::Driver( const CreationAbstractor<Car>& );
I attempted to make CreationAbstractor generic of up to N arguments:
template <class BaseT, class DerivedT = BaseT>
class Creator: public CreationAbstractor<BaseT>
{
private:
typedef boost::scoped_ptr<CreationAbstractor<BaseT> > ImplT;
ImplT impl_;
struct NoArgImpl: public CreationAbstractor<BaseT>
{ virtual BaseT* create() const{ return new DerivedT; } };
template <class F> struct Impl;
template <class A1>
struct Impl<void(A1)>: public CreationAbstractor<BaseT>
{
Impl( A1 a1 ): a1_( a1 ){}
virtual BaseT* create() const{ return new DerivedT( a1_ ); }
A1 a1_;
};
//etc...
public:
virtual BaseT* create() const
{
return impl_->create();
}
Creator(): impl_( new NoArgImpl ){ }
template <class A1>
Creator( A1 a ): impl_( new Impl<void(A1)>( a ) ){ }
//etc..
};
This seems to work fine, although I suppose you guys could
give me some pointers as to how to implement it better. The
problem that I have is that my original implementation had
only on type. Therefore:
template <class T>
class Creator: public CreationAbstractor<T>......(1)
This prohibit me from converting Creator<Derived> to
CreationAbstractor<Base>, despite my best efforts.
Does anybody know of a better implementation using nifty
conversions where a declaration as in (1) may suffice to do?
IOW:
const CreationAbstractor<Base>& a = const
CreationAbstractor<Derived>&...;compiles fine.
Regards,
Werner