[clang-tidy] Add `modernize-use-std-size` check
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
It would be useful to have a clang-tidy check that recognizes the classic hand-written array size idiom and suggests `std::size`, and similarly recognizes common signed-size spellings and suggests `std::ssize`.
Today code like this still appears regularly:
```cpp
auto n = sizeof(arr) / sizeof(arr[0]);
auto m = sizeof arr / sizeof *arr;
```
but in modern C++ the better spelling is:
```cpp
auto n = std::size(arr);
auto m = std::size(arr);
```
This is shorter, clearer, and directly expresses the operation instead of spelling it indirectly through `sizeof`.
A related improvement would be to catch common signed-size spellings such as:
```cpp
auto n = static_cast(v.size());
```
and suggest:
```cpp
auto n = std::ssize(v);
```
when that is clearly what the code is trying to express.
The check should be conservative.
For `std::size`, it should primarily target built-in arrays and other mechanically recognizable cases where the old `sizeof(arr) / sizeof(arr[0])` pattern is clearly being used to compute the number of elements.
For `std::ssize`, it should only trigger when the code is clearly performing a signed-size conversion rather than a broader numeric conversion.
Contributor guide
Assessment
This issue has not been assessed yet.