Compare commits
5 commits
1f65d803a7
...
30ffd90b2a
Author | SHA1 | Date | |
---|---|---|---|
Bruno BELANYI | 30ffd90b2a | ||
Bruno BELANYI | 70f99f21fa | ||
Bruno BELANYI | cb9545769d | ||
Bruno BELANYI | ab2fd4bb69 | ||
Bruno BELANYI | 80ef143ef2 |
|
@ -96,22 +96,22 @@ For example, a dummy file-system interface might look like the following:
|
||||||
```cpp
|
```cpp
|
||||||
struct Filesystem {
|
struct Filesystem {
|
||||||
virtual void write(std::string_view filename, std::span<char> data) = 0;
|
virtual void write(std::string_view filename, std::span<char> data) = 0;
|
||||||
virtual std::vector read(std::string_view filename) = 0;
|
virtual std::vector<char> read(std::string_view filename) = 0;
|
||||||
virtual void delete(std::string_view filename) = 0;
|
virtual void delete(std::string_view filename) = 0;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
You can then write `PosixFilesystem` which makes use of the POSIX API and
|
You can then write `PosixFilesystem` which makes use of the POSIX API and
|
||||||
interact with actual on-disk data, `MockFilesystem` which only works in-memory
|
interact with actual on-disk data, `MockFilesystem` which only works in-memory
|
||||||
and can be used for tests only, etc...
|
and can be used for testing, etc...
|
||||||
|
|
||||||
## Double dispatch
|
## Double dispatch through the Visitor pattern
|
||||||
|
|
||||||
Sometimes single dispatch is not enough, such as in the collision example at
|
Sometimes single dispatch is not enough, such as in the collision example at the
|
||||||
the beginning of this article. In cases where a computation depends on the
|
beginning of this article. In cases where a computation depends on the dynamic
|
||||||
dynamic type of *two* of its values, we can make use of double-dispatch by
|
type of *two* of its values, we can make use of double-dispatch by leveraging
|
||||||
calling a virtual method on the first value, which will call a virtual method
|
the Visitor design pattern. This is done by calling a virtual method on the
|
||||||
on the second value.
|
first value, which itself will call a virtual method on the second value.
|
||||||
|
|
||||||
Here's a commentated example:
|
Here's a commentated example:
|
||||||
|
|
||||||
|
@ -161,8 +161,8 @@ void collide(SpaceObject& first, SpaceObject& second) {
|
||||||
};
|
};
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
std::unique_ptr<SpaceObject> asteroid = std::make_unique<Asteroid>();
|
auto asteroid = std::make_unique<Asteroid>();
|
||||||
std::unique_ptr<SpaceObject> spaceship = std::make_unique<Spaceship>();
|
auto spaceship = std::make_unique<Spaceship>();
|
||||||
|
|
||||||
collide(*asteroid, *spaceship);
|
collide(*asteroid, *spaceship);
|
||||||
// Calls in order:
|
// Calls in order:
|
||||||
|
|
Loading…
Reference in a new issue