Re: Multimethods idioms and library support
On Feb 23, 4:07 pm, itaj sherman <itajsher...@gmail.com> wrote:
On Feb 23, 2:08 pm, James Kanze <james.ka...@gmail.com> wrote:
Multiple dispatch on open or large hierarchies is problematic in
general. For n derived classes, you need n^2 functions
(regardless of how the dispatch works), and when you add
a derived class, you have to define its interactions with all of
the existing classes. It's best avoided, but it is possible to
make it work: you need something like a
std::map<std::pair<std::type_index, std::type_index>,void (*)
(Base&, Base&)>
, where void Base::doSomething(Base& other) isn't virtual, but
looks up the actual (free) function to call in the map. Getting
the map initialized with all of the necessary functions is
non-trivial, but if you can provide a default Base&, Base&
functionality, and only need a few specific overrides, it might
be OK.
If you want an open hierarchy which supports all possible
combinations, the problem isn't the compiler; it's how to
provide all of the necessary functions. Each new class has to
provide all of the functions for it and all of the existing
classes. This quickly gets out of hand.
Ofcourse for k virtual parameters, the number of possible different
overrides is n^k. But so is the number of possible different static
overloads for a regular n-ary function in c++. But usually there are
some generalizations that are done on the possibilities that
practically cut them to around log(n)^k to n*log(n)^k sets and subsets
(just top of my head estimation).
Hopefully. At least if n is large.
In both cases that should be done using the hierarchy and
templates.
* For conviniency I'll base on the hipothetic language feature. But
what I mean is that it should be possible to create a library that
would support the same general constructs, just instead of syntax
you'll have to define classes and static variable of the library type.
It certainly isn't difficult to come up with a solution for
a given hierarchy. I'm not sure about a generic solution;
I haven't given it a try, but it seems like it should be
possible. The problem is to make the lookup as effective as
possible: if you require n^k functions, each for the most
derived class, you can use a hash table of some sort on the two
(or more) type_info's. If you don't, it's more difficult, since
type_info doesn't give you information about the base classes.
And you need to specify some sort of ordering: either first
match, and insist that the client codinsert in the correct
order (with the most specific functions where they will be found
first), or best match, and you have to define "best", evaluate
all matches, and define behavior in case of ambiguity. It's not
an easy task.
--
James Kanze