Skip to content

Commit 40b6404

Browse files
committed
[ADT] Introduce a static_cast_to
1 parent 8d9cd5b commit 40b6404

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

llvm/include/llvm/ADT/STLExtras.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1704,6 +1704,11 @@ auto sum_of(R &&Range, E Init = E{0}) {
17041704
return accumulate(std::forward<R>(Range), std::move(Init));
17051705
}
17061706

1707+
/// Returns a range where each value of `R` is static_cast to `T`
1708+
template <typename T, typename R> auto static_cast_to(R &&Range) {
1709+
return map_range(Range, [](const auto &V) { return static_cast<T>(V); });
1710+
}
1711+
17071712
/// Returns the product of all values in `Range` with `Init` initial value.
17081713
/// The default initial value is 1.
17091714
template <typename R, typename E = detail::ValueOfRange<R>>

llvm/unittests/ADT/STLExtrasTest.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1669,6 +1669,13 @@ TEST(STLExtrasTest, SumOf) {
16691669
EXPECT_EQ(sum_of(V3), 3.0f);
16701670
}
16711671

1672+
TEST(STLExtrasTest, StaticCastTo) {
1673+
std::vector<int32_t> R{1, 2, 3};
1674+
EXPECT_TRUE(all_of(R, [](auto V) { return sizeof(V) == sizeof(int32_t); }));
1675+
EXPECT_TRUE(all_of(static_cast_to<int64_t>(R),
1676+
[](auto V) { return sizeof(V) == sizeof(int64_t); }));
1677+
}
1678+
16721679
TEST(STLExtrasTest, ProductOf) {
16731680
EXPECT_EQ(product_of(std::vector<int>()), 1);
16741681
EXPECT_EQ(product_of(std::vector<int>(), 0), 0);

0 commit comments

Comments
 (0)