Xref: utzoo comp.object:560 comp.lang.c++:5746 Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!sun-barr!decwrl!ucbvax!bloom-beacon!eru!luth!sunic!liuida!mikpe From: mikpe@majestix.ida.liu.se (Mikael Pettersson) Newsgroups: comp.object,comp.lang.c++ Subject: Re: Continuations Message-ID: <1454@majestix.ida.liu.se> Date: 2 Dec 89 06:12:35 GMT References: <2664@bingvaxu.cc.binghamton.edu> <9624@pyr.gatech.EDU> <1623@odin.SGI.COM> <1989Nov28.183816.15252@odi.com> <9964@june.cs.washington.edu> <1989Nov29.225826.19483@odi.com> <10008@june.cs.washington.edu> <21989@brunix.UUCP> <1989Dec1.205817.5178@Neon.Stanf Organization: CIS Dept, Univ of Linkoping, Sweden Lines: 57 In article <1989Dec1.205817.5178@Neon.Stanford.EDU> mxh@sumex-aim.Stanford.EDU (Max Hailperin) writes: >As an asside to this discussion, it appears to me that closures can be >emulated relatively smoothely in C++. > [...] >I haven't actually used this technique (I'm lucky enough to have a >real lisp, instead of having to make C++ pretend it's one). I'd be >very interested to hear from anyone who has. I have. The idea is this: whenever you want to create a closure with type T, body B and (list of) free variables FV, you derive from an abstract base class `funcT' a class `foo_funcT' with instance variables `FV' and whose operator() does `B' when invoked. Something like this: (define (bar L) (let ((i 1)) (for-each (lambda (item) (princ i)(princ ":")(print item) (set! i (1+ i))) L))) (assuming a left-to-right calling order in for-each, this should print each item in the list L preceeded by its position in the list). The C++ emulation could look like: class funcT { // say: Obj->void public: virtual void operator()(Obj); }; class ObjList { ... friend void for_each(funcT&, ObjList); ... }; ... class foo_funcT : public funcT { int& i; public: foo_funcT(int& j) : i(j) {} void operator()(Obj); } void foo_funcT::operator()(Obj item) { cout << i << ":" << item << "\n"; ++i; } void bar(ObjList L) { int i = 1; foo_funcT fun(i); for_each(fun, L); } This technique handles downwards funargs quite nicely, upwards funargs require explicit heap allocation. -- Mikael Pettersson, Dept of Comp & Info Sci, University of Linkoping, Sweden email: mpe@ida.liu.se or ...!{mcsun,munnari,uunet,unido,...}!sunic!liuida!mpe Brought to you by Super Global Mega Corp .com