|
Boost : |
From: Anthony Liguori (anthony_at_[hidden])
Date: 2002-11-21 20:12:26
Peter Dimov wrote:
>template<class T> struct constructor
>{
> template<class A1> T * operator()(A1 const & a1)
> {
> return new T(a1);
> }
>};
>
>FactoryA b = constructor<B>();
>
Didn't even think to exploit the fact that function<B *(int)> is
assignable to function<A *(int)> :)
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.
>>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.
>
I see now that I should be quite careful what quick code samples I send
out to the list ;-)
Regards,
Anthony Liguori
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk