[clang-tools-extra] [clang-tidy] Add modernize-use-to-underlying check (PR #210459)

via cfe-commits cfe-commits at lists.llvm.org
Thu Aug 6 18:06:28 PDT 2026


================
@@ -0,0 +1,114 @@
+```{title} clang-tidy - modernize-use-to-underlying
+```
+
+# modernize-use-to-underlying
+
+Finds casts from a scoped enumeration (`enum class`) to an integer type and
+replaces them with a call to `std::to_underlying` (introduced in C++23).
+
+Converting a scoped enumeration to a hard-coded integer type is error-prone: if
+the enumeration's underlying type is later changed, every such cast silently
+becomes a narrowing, widening or sign-changing conversion. `std::to_underlying`
+always yields exactly the underlying type and keeps the code correct.
+
+Example:
+
+```cpp
+enum class Color : unsigned char { Red, Green, Blue };
+
+void f(Color c) {
+  // Before:
+  auto value = static_cast<unsigned char>(c);
+  // After:
+  auto value = std::to_underlying(c);
+}
+```
+
+The check matches `static_cast`, C-style casts and functional-style casts.
+
+## Precise and imprecise casts
+
+A cast is *precise* when its destination type is exactly the underlying type of
+the enumeration. A cast is *imprecise* when the destination type is an integer
+type other than the underlying type (a different width or signedness).
+
+
----------------
EugeneZelenko wrote:

```suggestion
```

https://github.com/llvm/llvm-project/pull/210459


More information about the cfe-commits mailing list