Skip to content

Commit

Permalink
[ADT] Backport std::to_underlying from C++23 (llvm#70681)
Browse files Browse the repository at this point in the history
This patch backports a one-liner `std::to_underlying` that came with C++23. This is useful for refactoring unscoped enums into scoped enums, because the latter are not implicitly convertible to integer types.

I followed libc++ implementation, but I consider their testing too heavy for us, so I wrote a simpler set of tests.
  • Loading branch information
Endilll committed Oct 30, 2023
1 parent 134c915 commit d0caa4e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
7 changes: 7 additions & 0 deletions llvm/include/llvm/ADT/STLForwardCompat.h
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,13 @@ auto transformOptional(std::optional<T> &&O, const Function &F)
return std::nullopt;
}

/// Returns underlying integer value of an enum. Backport of C++23
/// std::to_underlying.
template <typename Enum>
[[nodiscard]] constexpr std::underlying_type_t<Enum> to_underlying(Enum E) {
return static_cast<std::underlying_type_t<Enum>>(E);
}

} // namespace llvm

#endif // LLVM_ADT_STLFORWARDCOMPAT_H
17 changes: 17 additions & 0 deletions llvm/unittests/ADT/STLForwardCompatTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,21 @@ TEST(TransformTest, MoveTransformLlvm) {
EXPECT_EQ(0u, MoveOnly::Destructions);
}

TEST(TransformTest, ToUnderlying) {
enum E { A1 = 0, B1 = -1 };
static_assert(llvm::to_underlying(A1) == 0);
static_assert(llvm::to_underlying(B1) == -1);

enum E2 : unsigned char { A2 = 0, B2 };
static_assert(
std::is_same_v<unsigned char, decltype(llvm::to_underlying(A2))>);
static_assert(llvm::to_underlying(A2) == 0);
static_assert(llvm::to_underlying(B2) == 1);

enum class E3 { A3 = -1, B3 };
static_assert(std::is_same_v<int, decltype(llvm::to_underlying(E3::A3))>);
static_assert(llvm::to_underlying(E3::A3) == -1);
static_assert(llvm::to_underlying(E3::B3) == 0);
}

} // namespace

0 comments on commit d0caa4e

Please sign in to comment.