-
So I proudly came up with a few lines of mp-units stuff (yay) !
// mp-units concepts interface returning a QuantityOf<dimensionless>
constexpr auto total = bit_timing::num_quanta_in_bit(clock, prescaler, bitrate);
// how to handle dimensionlessness from a user perspective ?
// static_assert( total == 80);
// static_assert( total == 80 * one);
// static_assert(static_cast<int>(total) == 80); And for the percentage I struggle manipulating it: // this compiles
constexpr auto p = 0.8 * mp_units::percent;
// this too
auto do_something(QuantityOf<percent> auto p){ ... }
// this don't
do_something(p); This library is every year months better ! 👍🏽 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @Becheler, I am happy that you like the library 😃 Here are a few tips to get you started with dimensionless quantities. Declaring a percentage quantity can be done exactly as you stated: quantity p1 = 80 * percent; I prefer to use CTAD instead of if(p1 == 80 * percent) ...
if(p1 == 0.8 * one) ... Dimensionless quantities in a unit if(p1.in(one) == 0.8) ... Regarding your interface question, QuantityOf<dimensionless> auto do_something_1(QuantityOf<dimensionless> auto p){ return p; } In case you do not want it to be a template, and you really need a QuantityOf<dimensionless> auto do_something_2(quantity<percent> p){ return p; } Please also note that you can provide your own strongly typed dimensionless quantities with: inline constexpr struct my_ratio_or_count final : quantity_spec<dimensionless> {} my_ratio_or_count; With the above you can provide a specific interface like the following: void do_something_3(quantity<my_ratio_or_count[percent]> p){ ... } and call it with a strong or simple quantity: quantity p2 = my_ratio_or_count(80 * percent);
do_something_3(p2);
do_something_3(80 * percent); It will fail to compile if you try to call it with a different strong quantity: do_something_3(dimensionless(80 * percent)); // Compile-time error
do_something_3(other_ratio(80*percent)); // Compile-time error You can find some details here: https://godbolt.org/z/eYEK6nzWY. By the way, for the future, it always helps to have a link to Compiler Explorer in a question. Thanks to it, we can better understand your case and provide answers faster. |
Beta Was this translation helpful? Give feedback.
This is a perfectly valid scenario. This is exactly what I propose above.
If you do not want to have convertibility with pure numbers you can introduce custom domain-specific units. You can find more details and inspiration in: https://isocpp.org/files/papers/P3045R4.html#user-defined-quantities-and-units.