Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!wuarchive!decwrl!shelby!csli!keith From: keith@csli.Stanford.EDU (Keith Nishihara) Newsgroups: comp.lang.c++ Subject: Re: Design Problem Message-ID: <11258@csli.Stanford.EDU> Date: 4 Dec 89 17:25:40 GMT References: <22137@brunix.UUCP> Sender: keith@csli.Stanford.EDU (Keith Nishihara) Reply-To: Neil%teleos.com@ai.sri.com Organization: Center for the Study of Language and Information, Stanford U. Lines: 57 sdm@cs.brown.edu (Scott Meyers) writes: >I'm having trouble figuring out how to solve the following problem. Often >I find myself with a collection of objects of a given type, where some of >them define a particular function and some of them don't, and I want to >invoke the function on only those objects for which it is defined. For >example, I might have a collection of objects of type B, but only those >objects of type D (derived from B) define a function f; I'll want to invoke >f on those objects for which it is defined. How can I best accomplish >this? >To make things more concrete, I'm building graphs for representing >programs, and one of my base types is ARC. Derived from ARC are two >classes, EXECUTABLE_ARC and NONEXECUTABLE_ARC. Each of these types also >have subtypes, but that is immaterial. EXECUTABLE_ARCs define a function >evaluate(); NONEXECUTABLE_ARCs do not. The graph for a program consists >of a set of nodes and a set of arcs, and to execute the program, I need to >evaluate the nodes and arcs. So what I have is a set of ARCs, and I want >to call evaluate() on them, but only some of them define that function. >What I really want to be able to say is "if function f() is defined for >object o, then call o.f()". Is there a good way to acheive this effect? It seems to me that the virtual function defined on ARC with no ops for non executable arcs is what you need. However, one other approach which might be considered if you have lots of functions like execute, and especially if the functions applicable to executable arcs are from an open ended set, is as below: class executable_arc; class non_executable_arc; class arc { public: virtual executable_arc * executable() { return 0; } ... }; class executable_arc { public: executable_arc * executable() { return this; } ... }; main() { arc *p; executable *e; for(p = first; p; p = p->next()) if((e = p->executable()) != 0) e->execute(); } Neil/. Neil%teleos.com@ai.sri.com ...decwrl!argosy!teleos!neil