Преглед изворни кода

BinarySearch: constexpr support

Problem:
- It is not possible to perform a binary search at compile-time
  because `binary_search` is not `constexpr`-aware.

Solution:
- Add `constexpr` support.
Lenny Maiorani пре 4 година
родитељ
комит
a274a8e5a0
2 измењених фајлова са 17 додато и 2 уклоњено
  1. 2 2
      AK/BinarySearch.h
  2. 15 0
      AK/Tests/TestBinarySearch.cpp

+ 2 - 2
AK/BinarySearch.h

@@ -33,13 +33,13 @@
 namespace AK {
 
 template<typename T>
-int integral_compare(const typename RemoveConst<T>::Type& a, const typename RemoveConst<T>::Type& b)
+constexpr int integral_compare(const typename RemoveConst<T>::Type& a, const typename RemoveConst<T>::Type& b)
 {
     return a - b;
 }
 
 template<typename T, typename Compare>
-T* binary_search(Span<T> haystack, const typename RemoveConst<T>::Type& needle, Compare compare = integral_compare, size_t* nearby_index = nullptr)
+constexpr T* binary_search(Span<T> haystack, const typename RemoveConst<T>::Type& needle, Compare compare = integral_compare, size_t* nearby_index = nullptr)
 {
     if (haystack.size() == 0) {
         if (nearby_index)

+ 15 - 0
AK/Tests/TestBinarySearch.cpp

@@ -146,4 +146,19 @@ TEST_CASE(huge_char_array)
     delete[] span.data();
 }
 
+TEST_CASE(constexpr_array_search)
+{
+    constexpr Array<int, 3> array = { 1, 17, 42 };
+
+    constexpr auto test1 = *binary_search(array.span(), 1, AK::integral_compare<int>);
+    constexpr auto test2 = *binary_search(array.span(), 17, AK::integral_compare<int>);
+    constexpr auto test3 = *binary_search(array.span(), 42, AK::integral_compare<int>);
+    constexpr auto test4 = binary_search(array.span(), 99, AK::integral_compare<int>);
+
+    static_assert(test1 == 1, "Binary search should find value at compile-time.");
+    static_assert(test2 == 17, "Binary search should find value at compile-time.");
+    static_assert(test3 == 42, "Binary search should find value at compile-time.");
+    static_assert(test4 == nullptr, "Binary search should return nullptr for missing value at compile-time.");
+}
+
 TEST_MAIN(BinarySearch)