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

Unary lambdas in unevaluated contexts as a replacement for ratio/exponent

Open keris1 opened this issue 3 years ago • 7 comments

There are a couple of obstacles associated with using ratios to represent conversion factors, namely:

  • Nonlinear conversions are not possible
  • Ratio overflow occurs with some higher-dimensional quantities
  • Conversion types either need to be tracked (I'm new to the library, but I believe this is what's implemented), or we have to accept some level of forced type promotion (e.g. always assume the conversion factor is a long double, and therefore the converted value is always a long double)

On the contrary, allowing something like this could be an interesting thing to look into as a means of solving the above:

template<auto func> struct example_base_quantity { ... }; ... struct example_derived_quantity : example_base_quantity<[](auto&& x){ return std::sin(x); }> { ... };

What is not immediately clear to me, is how this will be optimized on various platforms. Perhaps one way to make the cost more clear is to also consider nullary lambdas that return scale factors. Nullary lambdas could simply be evaluated to a constant in the nested lambda definition. The alternative here is to hope that the compiler being used successfully flattens the recursion (I'm not convinced this would happen, but perhaps you might know the answer to this).

Another hidden advantage to this methodology is automatic type promotion. Something like this: [](auto&& x){ return 5 * x + 32; }; returns an integer when x is an integer, and a double when x is a double.

http://open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0315r1.pdf

keris1 avatar Oct 27 '20 16:10 keris1

This relates to #35, doesn't it?

JohelEGP avatar Oct 27 '20 17:10 JohelEGP

Yes. And also some aspects of #170, #169, and a few others.

keris1 avatar Oct 27 '20 17:10 keris1

This an interesting approach however I do not see how we could provide the required minimum functionality with it.

mpusz avatar Dec 31 '20 15:12 mpusz

Which pieces are missing? Or, alternatively, what are the requirements you're trying to meet?

keris1 avatar Dec 31 '20 16:12 keris1

I know that your example is a simplification and I have to think a bit more about it. For now, I do not clearly see how to for example construct a quantity of speed from the division of quantity of length and time. Also, I am not sure how to handle different units and their conversion ratios in an orthogonal way (i.e. 1m + 1km = 1001m).

mpusz avatar Dec 31 '20 20:12 mpusz

I'll see if I can come up with a more concrete example in the next few days. I think I understand your concern

keris1 avatar Dec 31 '20 22:12 keris1

Also related to #195. https://github.com/mpusz/units/issues/209#issuecomment-965231924 implies that we'd have to drop support for Clang 12 and probably 13 too. And 14 at worst.

JohelEGP avatar Nov 10 '21 14:11 JohelEGP