@keadamander@mastodon.social It's in the testcase I posted on Godbolt:
https://godbolt.org/z/K7fYGcx8h
@codewiz What would Rust do? Not very familiar with Rust but it seems like it would give you a compile error if the function were a const fn , according to https://doc.rust-lang.org/reference/const_eval.html. If it weren't a const fn, you'd get a panic in debug mode and silent overflow in release? And if it were a const fn that returned Option/Error, then you'd be safe but have to unwrap at runtime I think. Would be nice if you could configure a const fn to cause a compile error when returning None/Error.
@jeeves I had this same question on my mind, and I wanted to write a testcase as soon as I find some time.
Feel free to beat me at it, and please share your code on Godbolt!
@codewiz My previous Toot was wrong so I deleted it; it turns out Rust is actually panicking at runtime, not compile time on integer overflow in a const fn: https://rust.godbolt.org/z/hvPY1YvGz
@codewiz I got it to error out at compile time: https://rust.godbolt.org/z/qhhTxb8hr. Had to change from calling the const fn in the argument list of println!() to first assigning the result of the const fn to a const variable, then calling println!() with that variable, so it would evaluate the const fn in a const context (defined at https://doc.rust-lang.org/reference/const_eval.html#const-context).
@jeeves Ok, overflowing in constant expressions is an error also with C++, but only with signed integers:
https://rust.godbolt.org/z/e947Pq8s6
@jeeves Followup on the unnecessarily hard problem of getting compile-time errors for overflows in conversions between std::chrono::duration constants:
https://godbolt.org/z/7E9MMMMfz
TL;DR: too complicated and unergonomic until C++ adds constexpr function parameters.
@codewiz could you have the conversion function return the equivalent of Rust's Result type and create a STATIC_UNWRAP macro that hides the template grossness?
@jeeves Not feasible in C++ for cases like initializing global constants and passing durations to constructors (without using exceptions!)
I wanted to see if I could get better compile-time overflow checks with Rust, but the limitations are similar: arguments of const functions are not themselves compile-time constants that you could check with assert!().
So this is what I could come up with:
https://godbolt.org/z/5zf1earKT
Even in Rust nightly, support for constant evaluation is still very limited compared to C++20's:
https://doc.rust-lang.org/reference/items/generics.html
At this time, you can't even pass float parameters or enums, let alone structs.
There's ongoing work to expand the capabilities of constant evaluation in Rust, but it will take years before they can close the gap with C++, which is not standing still:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/#mailing2022-01