// A simple example of wrapping via template function specialization.
#include <string>
using namespace std;
// This handle requires that the managed class support the clone() function to
// create instance copies.
template < typename T >
class handle {
public:
handle() : tp(0) { }
handle(T * tp) : tp(tp) { }
~handle(void) {
delete tp;
}
handle(const handle & th) : tp(th.tp ? clone(th.tp) : 0) { }
handle & operator = (const handle & th) {
if (this != &th) {
delete tp;
tp = th.tp ? clone(th.tp) : 0;
}
return *this;
}
operator bool (void) const {
return tp;
}
T & operator * (void) {
assert(tp);
return *tp;
}
T * operator -> (void) {
assert(tp);
return tp;
}
private:
T * tp;
};
// This class doesn't implement a clone() function.
class turtle {
public:
turtle(const string &) { }
void draw(unsigned){ }
};
// The generic definition of the clone() function: call the clone() implemented
// by the instance being pointed to.
template < typename T >
T * clone(const T * tp) {
return tp->clone();
}
// A specialization of clone for turtles, implemented using the (default) copy
// constructor and operator new.
template < >
turtle * clone(const turtle * tp) {
return new turtle(*tp);
}
// And there you go.
int main() {
handle<turtle> t1h = new turtle("+ [ - f f]");
handle<turtle> t2h = t1h;
}
// $Log: tf-wrapping.cc,v $
// Revision 1.1 2002/04/28 01:13:37 rclayton
// Initial revision
//
syntax highlighted by Code2HTML, v. 0.9