From bd5f94746956a69fe6b835a4b34c92c5c5c8e426 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Thu, 3 Nov 2022 11:22:24 +0100 Subject: [PATCH] posts: multiple-dispatch: add 'yomm2' example --- .../index.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/content/posts/2022-11-02-multiple-dispatch-in-c++/index.md b/content/posts/2022-11-02-multiple-dispatch-in-c++/index.md index f179561..838de49 100644 --- a/content/posts/2022-11-02-multiple-dispatch-in-c++/index.md +++ b/content/posts/2022-11-02-multiple-dispatch-in-c++/index.md @@ -290,3 +290,40 @@ In the meantime, one can find some libraries (like [`yomm2`][yomm2]) that reduce the amount of boiler-plate needed to emulate this feature. [yomm2]: https://github.com/jll63/yomm2 + +```cpp +#include + +struct SpaceObject { + virtual ~SpaceObject() = default; +}; + +struct Asteroid : SpaceObject { /* fields, methods, etc... */ }; + +struct Spaceship : SpaceObject { /* fields, methods, etc... */ }; + +// Register all sub-classes of `SpaceObject` for use with open methods +register_classes(SpaceObject, Asteroid, Spaceship); + +// Register the `collide` open method, which dispatches on two arguments +declare_method(void, collide, (virtual_, virtual_)); + +// Write the different implementations of `collide` +define_method(void, collide, (Asteroid& left, Asteroid& right)) { /* work */ } +define_method(void, collide, (Asteroid& left, Spaceship& right)) { /* work */ } +define_method(void, collide, (Spaceship& left, Asteroid& right)) { /* work */ } +define_method(void, collide, (Spaceship& left, Spaceship& right)) { /* work */ } + + +int main() { + yorel::yomm2::update_methods(); + + auto asteroid = std::make_unique(); + auto spaceship = std::make_unique(); + + collide(*asteroid, *spaceship); // Calls (Asteroid, Spaceship) version + collide(*spaceship, *asteroid); // Calls (Spaceship, Asteroid) version + collide(*asteroid, *asteroid); // Calls (Asteroid, Asteroid) version + collide(*spaceship, *spaceship); // Calls (Spaceship, Spaceship) version +} +```