Compare commits

..

No commits in common. "30ffd90b2a971c26f41a2f14aa52d59add3adf0b" and "1f65d803a7ddf23b522ab927c78d7dde5dafe0ad" have entirely different histories.

View file

@ -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<char> read(std::string_view filename) = 0; virtual std::vector 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 testing, etc... and can be used for tests only, etc...
## Double dispatch through the Visitor pattern ## Double dispatch
Sometimes single dispatch is not enough, such as in the collision example at the Sometimes single dispatch is not enough, such as in the collision example at
beginning of this article. In cases where a computation depends on the dynamic the beginning of this article. In cases where a computation depends on the
type of *two* of its values, we can make use of double-dispatch by leveraging dynamic type of *two* of its values, we can make use of double-dispatch by
the Visitor design pattern. This is done by calling a virtual method on the calling a virtual method on the first value, which will call a virtual method
first value, which itself will call a virtual method on the second value. 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() {
auto asteroid = std::make_unique<Asteroid>(); std::unique_ptr<SpaceObject> asteroid = std::make_unique<Asteroid>();
auto spaceship = std::make_unique<Spaceship>(); std::unique_ptr<SpaceObject> spaceship = std::make_unique<Spaceship>();
collide(*asteroid, *spaceship); collide(*asteroid, *spaceship);
// Calls in order: // Calls in order: