Hacker News new | past | comments | ask | show | jobs | submit login

Hmm, I don't have much to disagree with for this link, unlike many things from that site.

One minor point - the method implementations should not be `static`, so that you can support further subclassing and reuse the base class implementations.

Note that to support both virtual and non-virtual method binding, the dispatcher also needs to be exported (with the same signature). This is already the case in the linked code but a point isn't made of it; it can be tempting to abuse `inline` but remember that is primarily about visibility [1].

It also doesn't mention how to implement `dynamic_cast` (practically mandatory for multimethod-like things), which can be quite tricky, especially in the multiple-inheritance case and/or when you don't know all the subclasses ahead of time and/or when you have classes used in across shared libraries. There are cases where you really do need multiple vtables.

Virtual inheritance, despite its uses, is probably a mistake so it's fine that it ignores that.

[1]: https://stackoverflow.com/a/51229603/1405588




Is there anything you need multimethods for that can't be patched with visitors and other design patterns? They have always seemed to me like a neat feature that are devilishly tricky to implement and difficult to reason about for the average programmer.


You don't need multimethods per se, but you need something and `dynamic_cast` is usually easiest (and with reasonable restrictions, most efficient).

Overloaded operators is a major category of problem here. The "which subclass (if any) is more derived" might be done by the compiler proper, but that still needs to use the cast internally. And of course if you ignore operator overloading, you're just pulling a Java and mandating extra verbosity; the user's problem still has to be solved the exact same way.

(most other use cases for multimethods I don't find compelling)


Successful dynamic_casts are fast. But failing dynamic_casts usually involve at least one strcmp and are extremely expensive.

https://gcc.gnu.org/legacy-ml/gcc-patches/2009-07/msg01239.h...


For the particular set of tradeoffs made by C++. When rolling your own you don't have to do make the same choices.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: