template < typename T > class handle { handle(const handle & th) : tp(th.tp ? th.tp->clone() : 0) { } };
T
has to support the clone()
function.
template < typename T > ostream & operator << (ostream & os, const T & t) { return os << t; }
T
has to support <<
.
clone()
to the widget class.
clone()
$ cat t.cc class turtle { public: turtle(const string &) { } void draw(unsigned){ } }; int main() { handle<turtle> t1h = new turtle("+[-ff]"); handle<turtle> t2h = t1h; } $ g++ -c -ansi -pedantic -Wall t.cc t.cc: In copy constructor handle<T>::handle(const handle<T>&) [with T = turtle]: t.cc:69: instantiated from here t.cc:17: no function for turtle::clone() $
$ cat t.cc class wrapped_turtle { public: wrapped_turtle(const string & s) : t(s) { } void draw(unsigned i) { t.draw(i); } wrapped_turtle * clone(void) { return new wrapped_turtle(*this); } private: turtle t; }; int main() { wrapped_turtle * wt1p = new wrapped_turtle("+[-ff]"), * wt2p = wt1p->clone(); } $ g++ -o t -ansi -pedantic -Wall t.cc $ ./t $
C::clone()
exists, instantiate Handle
.
cloner()
is created via template-function magic.
C::clone()
doesn't exist, create a special cloner()
to deal
with it.
// definition 1 template < typename T1, typename T2 > void f(T1 a1, T2 a2) { T1 v1; } // definition 2 template < > void f(int * a1, pair<double, double> a2) { int * v1; }
Here T1
is replaced by int *
and T2
is replaced by
pair<double,double>
.
f(&i, make_pair(1.0, 3.14))
template < typename T > T * clone(const T * tp) { return tp->clone(); }
Replace
handle < template T > handle<T>::handle(const handle & th) : tp(th.tp ? th.tp->clone() : 0) { }
with
handle < template T > handle<T>::handle(const handle & th) : tp(th.tp ? cloner(th.tp) : 0) { }
clone()
instance has been moved outside the handle
class.
$ cat t.cc class turtle { public: turtle(const string &) { } void draw(unsigned){ } }; template < > turtle * cloner(const turtle * tp) { return new turtle(*tp); } int main() { handle<turtle> t1h = new turtle("+[-ff]"); handle<turtle> t2h = t1h; } $ g++ -o t -ansi -pedantic -Wall t.cc $ ./t $
See the complete code.
This page last modified on 23 December 2002.