mp-units icon indicating copy to clipboard operation
mp-units copied to clipboard

Should we encourage deriving from `quantity` and `quantity_point`?

Open mpusz opened this issue 10 months ago • 3 comments

A long time ago, one of the contributors changed the Quantity concept to allow also classes derived from the quantity class template. At this point, I thought this idea was OK. However, as C++ standardization approaches fast, we may have to reconsider this decision.

The problem with concept-based programming is that concepts do not allow implicit conversion for function arguments. So the following two function templates are not equivalent:

template<auto R, typename Rep>
void foo(const quantity<R, Rep>& q);

template<Quantity Q>
void boo(const Q& q);

C++ library never encouraged deriving from its own class templates, but all operators worked fine if someone did, thanks to the foo approach.

In mp-units, in some places, we use boo approach. Directly or indirectly, we require a template dependent name to satisfy Quantity or QuantityPoint concepts. This would prevent the derived classes from working if those concepts were refactored to accept the type explicitly.

On the other hand, explicitly stating that a Quantity is also everything derived from quantity may be controversial.

We should consider changing Quantity and QuantityPoint concepts to do explicit match and carefully refactor the cases where it is used incorrectly.

mpusz avatar Feb 14 '25 20:02 mpusz

I assume we want to disallow inheriting from quantity and quantity_point. Seems like a pretty suspect operation.

Do you (or does anyone else) have a concrete use case where deriving from quantity or quantity_point makes good sense?

chiphogg avatar Feb 16 '25 19:02 chiphogg

@chiphogg, my understanding is that some users derive from quantity to add more information to it. Here is an example: https://github.com/mpusz/mp-units/blob/7102a4f63d3efe10ecb10486c44eedf80c0f9976/test/static/quantity_test.cpp#L400-L432.

mpusz avatar Feb 17 '25 19:02 mpusz

That looks incredibly complex and error prone! I also couldn't tell what new information was actually being added, or whether this is all just boilerplate.

My instinct is still to lean on standard guidance to "prefer composition to inheritance". I'm wary of having other types that purport to model the "is-a" relationship with quantity. If you (or anyone else!) have some examples of real concrete use cases that require inheriting from quantity, I'd be interested to see them, but this one just seems like a placeholder to prove that inheritance is possible.

chiphogg avatar Feb 20 '25 21:02 chiphogg