Peter Dimov wrote:
Didn't even think to exploit the fact that function<B *(int)> is assignable to function<A *(int)> :)template<class T> struct constructor { template<class A1> T * operator()(A1 const & a1) { return new T(a1); } };FactoryA b = constructor<B>();
I only have one problem with this approach. The fact that one can do:
constructor<B> b;
constructor<A> a;
std::auto_ptr<B>(b()); // this will be quite valid
function<A *(int)> f = b; // this will also be valid
// yet
a = b; // is not valid
The easiest way to fix this is to entirely avoid the type argument and make constructor a function that returns a function object.
I also went ahead and changed the template parameter to take a function type so that different constructors can be used. The syntax is now:
// Store a functor for B::B(int, int) in f
boost::function<A *(int, int)> f = boost::constructor<B *(int, int)>();
std::auto_ptr<A>(f(10, 15)); // returns static_cast<A *>(new B(10, 15));
I'm in the process of getting clearance from employer to release this stuff so I should have it all up on my site within a few days... I'm writing a metaclass library and this will be the virtual constructor portion.
I see now that I should be quite careful what quick code samples I send out to the list ;-)FactoryA c;
A *a = b(10); // Returns new B(10)
c = b;
delete a;
a = c(15); // Returns new B(10)
;-) Change 'T*' to auto_ptr<T> or shared_ptr<T> according to taste.
Regards,
Anthony Liguori
_______________________________________________
Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost