Ranges (C++20)

3 years ago by thomask to c/cpp

At work-work, we try to stick to the forefront of C++ language development: C++20 all the time, C++23 as it shows up and is available in compilers. It’s a weird mix sometimes with a codebase that has a lengthy history. A while back I bumped into a for loop, tried to be clever and then hit limitations of Clang – and those limitations are sometimes relevant for KDE code that lands in FreeBSD, which is why I’m writing about it.
load all comments
cgtjsiwy 3 points 3 years ago

In C++23, you can zip the two arrays, so there's no need to declare an otherwise useless index variable:

int stdSumOfValidDataPoints(const MyData& data)
{
    using namespace std;
    auto&& r = ranges::views::zip_transform(
        [](int data, bool valid){return data * valid;},
        data.dataPoint,
        data.dataPointIsValid
    );
    return accumulate(begin(r), end(r), 0);
}

Unfortunately, the current implementation of zip_transform in GCC doesn't understand that the output length is constant 8, so it does needless cmps every iteration to check if it should stop iterating. (Godbolt)

path: 0 565951, hotness: undefined, score: 3, children: 0
cpp
cpp

@programming.dev

login for more options
2381
416
45

The center for all discussion and news regarding C++.

Rules

  • Respect instance rules.
  • Don't be a jerk.
  • Please keep all posts related to C++.

go to feed...