News for hackers. Stuff that matters.
Re:New C++ features in GCC 12 by arcticbull on Sunday May 01, 2022 @01:45PM (#31226988)
`std::is_constant_evaluated` seems bananas to me - looks like a great way to end up with almost untraceable bugs, where the same function may or may not have bugs depending on whether its evaluated at runtime or at compile time. Are there good ways to run unit tests against both const and non-const evaluations?!

But then again, most new C++ features seem bananas to me, so I wouldn't read into it.

Re:New C++ features in GCC 12 by jcelerier on Sunday May 01, 2022 @05:58PM (#31229096)
How would you implement something like strlen so that you have the strict, hard guarantee that strlen("foo") is evaluated at compile-time?
Re:New C++ features in GCC 12 by arcticbull on Sunday May 01, 2022 @07:09PM (#31229630)
I'm saying a conditional branch that offers a different path of execution for a constant evaluation than for a runtime evaluation gives you a function that behaves differently in different contexts.

In Rust, for instance, constant functions have to evaluate the same in both compile time and run time - you can't have a different code path depending on which. If you want that, make two functions.

Trivially:

  constexpr bool is_even(int x) {
    if (std::is_constant_evaluated()) {
      return true;
    } else {
      return ((x % 2) == 0);
    }
  }
How would you unit test this in a way that catches that only the constant evaluation is broken?
Re:New C++ features in GCC 12 by StephanTLavavej on Sunday May 01, 2022 @07:24PM (#31229718)
Here’s what we do in MSVC’s STL:

    constexpr bool test_is_even() {
        assert(is_even(0));
        assert(!is_even(1));
        // … more test coverage
        return true;
    }
    int main() {
        test_is_even(); // runtime coverage
        static_assert(test_is_even()); // compile-time coverage
This lets us run all test cases at both runtime and compiletime. (The static_assert performs constant evaluation, and if an assert within test_is_even would fail, it won’t be a constant expression.)
Re:New C++ features in GCC 12 by arcticbull on Sunday May 01, 2022 @08:11PM (#31230006)
That's very cool, thank you for sharing!
Re:New C++ features in GCC 12 by jcelerier on Monday May 02, 2022 @12:42AM (#31231554)
But then you can't have generic functions that are efficient at run-time and work at compile-time ?

This feature is added to c++ not for fun but because if you can't have a run-time branch that will do some AVX-fu, or invoke some runtime function from BLAS or LAPACK, the whole "evaluate at compile-time" thing is... Not useless but not far either