[ADT] add initializer list specialization for is_contained

Adding an initializer list specialization for is_contained allows for
compile-time evaluation when called with a constant or runtime
evaluation for non-constant values.

This patch doesn't add any uses of this template, but that is coming in
a subsequent patch.

Reviewed By: pete

Differential Revision: https://reviews.llvm.org/D122079
This commit is contained in:
Chris Bieneman 2022-03-28 16:33:16 -05:00
parent 6c32075d29
commit b39f437757
2 changed files with 34 additions and 0 deletions

View File

@ -1657,6 +1657,15 @@ bool is_contained(R &&Range, const E &Element) {
return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
}
template <typename T>
constexpr bool is_contained(std::initializer_list<T> Set, T Value) {
// TODO: Use std::find when we switch to C++20.
for (T V : Set)
if (V == Value)
return true;
return false;
}
/// Wrapper function around std::is_sorted to check if elements in a range \p R
/// are sorted with respect to a comparator \p C.
template <typename R, typename Compare> bool is_sorted(R &&Range, Compare C) {

View File

@ -964,4 +964,29 @@ TEST(STLExtrasTest, TypeAtIndex) {
(std::is_same<double, llvm::TypeAtIndex<2, int, float, double>>::value));
}
enum Doggos {
Floofer,
Woofer,
SubWoofer,
Pupper,
Pupperino,
Longboi,
};
TEST(STLExtrasTest, IsContainedInitializerList) {
EXPECT_TRUE(is_contained({Woofer, SubWoofer}, Woofer));
EXPECT_TRUE(is_contained({Woofer, SubWoofer}, SubWoofer));
EXPECT_FALSE(is_contained({Woofer, SubWoofer}, Pupper));
EXPECT_FALSE(is_contained({}, Longboi));
static_assert(is_contained({Woofer, SubWoofer}, SubWoofer), "SubWoofer!");
static_assert(!is_contained({Woofer, SubWoofer}, Pupper), "Missing Pupper!");
EXPECT_TRUE(is_contained({1, 2, 3, 4}, 3));
EXPECT_FALSE(is_contained({1, 2, 3, 4}, 5));
static_assert(is_contained({1, 2, 3, 4}, 3), "It's there!");
static_assert(!is_contained({1, 2, 3, 4}, 5), "It's not there :(");
}
} // namespace