4 ms·
Like many language features, it can and will be abused; and like overloaded operators it may be very difficult to determine where a custom suffix is even define
by makecheck 15y ago
Like many language features, it can and will be abused; and like overloaded operators it may be very difficult to determine where a custom suffix is even defined.
It will definitely be nice in a few places. For instance I can imagine that writing 01011011_b (after defining "_b") would be very handy.
I think examples that attach units instead of just metric prefixes are missing the point because the result is always a number (or a string), not a particular kind of object. If you say "assert(1_kg == 2.2_lb)" that is completely misguided because you haven't specified the context; again, these are just numbers so what do you end up with, kilograms or pounds or something else? Far better to name suffixes only in terms of scaling factors, e.g. "_kilo" or "_K" defined as 1000x would be applicable in more situations.
- SamReidHughes 15y agoAdding units is quite reasonable, but of course the 1_kg == 2.2_lb assertion can fail simply because if you multiply 2.2 by 1 / 2.2, you're not gonna get 1. And when adding units you certainly should not get numbers. 1_kg should not be a double. It should be a unit<double, mass> or something. And 1_kg * 1_kg should be a unit<double, mul<mass, mass>>? Presumably it's possible to make something like that work in the C++ type system. You have to be careful about 01011011_b. I'd guess that gets parsed as an octal constant. But if you write 11011010_b, that'll get parsed as a decimal constant.
- charliesome 15y ago> because if you multiply 2.2 by 1 / 2.2, you're not gonna get 1. But if you multiply 2.2 by 1 / 2.2, you should get within 1 ± DBL_EPSILON (which is how the hypothetic Weight::operator== should be implemented...)
- makecheck 15y agoI didn't have that right, it seems the result certainly can be a class. And that would avoid the units problem. Though in the examples I've seen it wasn't clear if they were returning a class. With raw numerical values the results are definitely unpredictable. For example maybe the program considers numerical values to be measured in ounces, in which case "2.2_lb" becomes the number "35.2"; or maybe it thinks everything is metric, measured in grams. There is not just one reasonable way to pick a number to represent an expression. I am fairly sure that a leading zero cannot be a problem with custom literals; I'd expect the compiler to parse the whole thing and see the suffix before deciding what type of literal it is (i.e. the "_b" handler would get to read everything raw, including the leading zero).