All of the distribution classes in the standard library seem to have very similar structures. From what I can see at a cursory glance, they all have the same member functions. Is there a reason as to why the standard distribution classes found within the standard random library do not inherit from a singular generalised "distribution" class?
Asked
Active
Viewed 96 times
1
-
2Even **if** it was desired, the `operator()` method of distributions is templated on the generator, and you can't have a templated virtual function. Without a polymorphic interface, inheritance doesn't bring anything to the table here. – Sep 16 '21 at 05:58
-
1On an abstract level if your goal is to reduce code duplication inheritance shouldn't be the first thing to look for anyway (it can be a practical choice). Inheritance should used to reuse behavior (semantics). And as Frank said templates and inheritance don't mix. If you want todo code reuse with templates you can use the mixin approach. (https://www.fluentcpp.com/2017/12/12/mixin-classes-yang-crtp/). And sometimes just doing a bit of code duplication can be easier to maintain. Only one set of tests to run instead of all the code where code has been reused (its a tradeof) – Pepijn Kramer Sep 16 '21 at 06:16
-
1It's also worth mentioning that the standard only specifies an API, how code is reused vs duplicated within a given implementation of the standard library is up to the implementors. Distributions could very well share a base class (if it makes sense to the implementors), but they don't *have* to, and if they do, then it's going to be hidden from the users. – Sep 16 '21 at 06:35
-
1@Frank Namely: _"An implementation may derive any class in the C++ standard library from a class with a name reserved to the implementation."_ [(derivation/1)](http://eel.is/c++draft/library#derivation-1). – Daniel Langr Sep 16 '21 at 06:43
-
Short answer because templates. Longer answer when using templates all of the (implementation) code has to be visible at the usage site. This makes optimisation possible (not possible with virtual dispatch) and the template operations optimise down to (almost) the equivalent of hand-rolled-code. – Richard Critten Sep 16 '21 at 08:23
-
2Does this answer your question? [Why is the C++ STL is so heavily based on templates? (and not on \*interfaces\*)](https://stackoverflow.com/questions/1039853/why-is-the-c-stl-is-so-heavily-based-on-templates-and-not-on-interfaces) – Richard Critten Sep 16 '21 at 08:28