1- :example: ../examples/rolex
1+ :example: ../examples
22
33## Multiple Dispatch
44
@@ -8,23 +8,60 @@ equally in overrider selection, following the same rules as those governing
88overload resolution - except that the selection happens at runtime, and takes
99into account the argument's dynamic types.
1010
11- Multiple dispatch is occasionally useful, and, when it is needed, it can be
12- difficult to implement correctly and efficiently by hand. For example, given the following classes:
11+ Multiple dispatch is occasionally useful. When it is needed, it can be difficult
12+ to implement correctly and efficiently by hand. For example, given the following
13+ classes:
1314
1415[source,c++]
1516----
16- include::{example}/7/main.cpp[tag=classes]
17+ include::{example}/rolex/ 7/main.cpp[tag=classes]
1718----
1819
19- We want to implement an `approve` method that determines who can make what kind
20- of expenses. Employees can take any public transportation; managers can also
21- take a taxi, for a ride cost up to $100.00; and founders can take any
22- transportation, including a private jet. This can be expressed like so:
20+ We want to implement a function - `approve` - that determines who can make what
21+ kind of expenses. The rules are:
22+
23+ - By default, an expense is rejected.
24+
25+ - Employees can take any public transportation.
26+
27+ - Managers can also take a taxi, for a ride cost up to $100.
28+
29+ - Founders can take any transportation, including a private jet.
30+
31+ This is a case of multiple dispatch: the outcome depends on two parameters. It
32+ can be implemented as a method with two virtual arguments. The four rules can be
33+ expressed as four overriders:
34+
35+ [source,c++]
36+ ----
37+ include::{example}/rolex/7/main.cpp[tag=approve]
38+ ----
39+
40+ ### Ambiguities
41+
42+ Because `approve` understands inheritance, we don't have to specify an overrider
43+ for every combination (5 role classes x 6 expense classes = 30 combinations).
44+
45+ Just like with overload resolution, ambiguities can arise. Let's look at another
46+ example - matrix addition:
2347
2448[source,c++]
2549----
26- include::{example}/7/ main.cpp[tag=approve ]
50+ include::{example}/ambiguities/1/ main.cpp[tag=content ]
2751----
2852
29- Note that `approve` takes advantage of inheritance to avoid listing all possible
30- cases explicitly. This is important, because the number of cases grows
53+ The programs terminates with the following error message:
54+
55+ ```
56+ ambiguous
57+ Aborted (core dumped)
58+ ```
59+
60+ This is because the call to `add(a, b)` is ambiguous: both overriders are equally
61+ good matches. The solution is to add an overrider for the case where both
62+ arguments are `SparseMatrix` :
63+
64+ [source,c++]
65+ ----
66+ include::{example}/ambiguities/2/main.cpp[tag=content]
67+ ----
0 commit comments