Question

This is a question regarding how Multiple Dispatch works.

Suppose that we have a type hierarchy like this:

Drawable -> Shape -> Polygon -> Rectangle

And there are three functions (This is a pseudo-code):

void func(Rectangle*, Drawable*, Drawable*) ...
void func(Rectangle*, Rectangle*, Drawable*) ...
void func(Polygon*, Rectangle*, Rectangle*) ...

And suppose that this is a piece of code:

Drawable* x = create_rectangle();
Drawable* y = create_rectangle();
Drawable* z = create_rectangle();

Obviously types of x,y,z are all Drawable but they contain instances of a Rectangle. Which function will be called if I write: func(x, y, z)?

We don't have any function which matches exact types of x, y and z so what happens in this case?

Was it helpful?

Solution

You can implement this several ways. The way that would be least surprising to me is to prefer the least abstract match and to look for it from left to right.

In this case that means you'd call:

void func(Rectangle*, Rectangle*, Drawable*) ...

OTHER TIPS

I can't speak for other languages, but given your posted code,

func(x, y, z);

is an error in C++.

See http://ideone.com/cEJyfA.

If you decide to implement dynamic dispatch based on multiple arguments, you'll have to build the algorithm yourself. If you do that, one sensible strategy would be to use the best matching function based on the type of the object the arguments point to, from left to right.

If you are able to implement such a mechanism,

func(x, y, z);

should ultimately call:

void func(Rectangle*, Rectangle*, Drawable*);
Licensed under: CC-BY-SA with attribution
scroll top