au icon indicating copy to clipboard operation
au copied to clipboard

Allow `.as<Rep>()` syntax on a Quantity

Open hoffbrinkle opened this issue 1 year ago • 2 comments

With the introduction of Constant, there was an API introduced for those that allows the Rep to be indicated without changing the Unit of the constant. Specifically, one can use .as<Rep>() to return a Quantity with the desired Rep from a Constant.

I find this to be a natural API, and often find myself trying to do the same thing on a Quantity when I want a Quantity with a specific Rep. We have several other options when this needs to be done:

  1. .coerce_as<Rep>(Unit)
  2. .as<Rep>(Unit)
  3. rep_cast<Rep>(Quantity)

The first one is scary. The second option works, but forces me know the Unit even if I don't want the Unit to change. The third option is does a static_cast on the underlying value. I think the third option is best suited for my use cases.

What I'm thinking is an API that is .as<Rep>() if I don't want the unit to change, with as much of the "don't accidentally shoot yourself in the foot" checking as the library can provide.

hoffbrinkle avatar Jul 04 '24 17:07 hoffbrinkle

Fascinating! I strove to make Au's interfaces a kind of "composable grammar", so people could learn the meaning of words like as and in and apply them consistently (e.g., round_as vs. round_in). This implication hadn't occurred to me, but it makes sense.

It also suggests that q.coerce_as<R>() might be a good synonym for rep_cast<R>(q). If we add q.as<R>(), it seems safe to say we should add the coerce version too. I'm less sure about whether we would want to remove rep_cast once we do.

chiphogg avatar Jul 06 '24 14:07 chiphogg

Something we'll need to consider: how will this interact with policy arguments? I think we want the default to include safety checks, so we'll want a policy argument version. But that could be a little tricky to distinguish from the single-argument version for units. We'll probably need to use SFINAE on all overloads, and we'll need to watch out for the performance costs.

chiphogg avatar Aug 27 '25 15:08 chiphogg