Skip to content

Commit 00478de

Browse files
Abseil Teamcopybara-github
Abseil Team
authored andcommitted
Mark non-modifying container algorithms as constexpr for C++20.
This change marks Abseil's non-modifying sequence operations including absl::linear_search and absl::c_linear_search as constexpr when building with C++20. PiperOrigin-RevId: 659812405 Change-Id: I8dc2cee873f30531b2eb8fb3da12085505a43a1a
1 parent 809e5de commit 00478de

File tree

4 files changed

+299
-51
lines changed

4 files changed

+299
-51
lines changed

absl/algorithm/algorithm.h

+2-2
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ using std::rotate;
5353
// n = (`last` - `first`) comparisons. A linear search over short containers
5454
// may be faster than a binary search, even when the container is sorted.
5555
template <typename InputIterator, typename EqualityComparable>
56-
bool linear_search(InputIterator first, InputIterator last,
57-
const EqualityComparable& value) {
56+
ABSL_INTERNAL_CONSTEXPR_SINCE_CXX20 bool linear_search(
57+
InputIterator first, InputIterator last, const EqualityComparable& value) {
5858
return std::find(first, last, value) != last;
5959
}
6060

absl/algorithm/algorithm_test.cc

+13-3
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,9 @@
1414

1515
#include "absl/algorithm/algorithm.h"
1616

17-
#include <algorithm>
18-
#include <list>
17+
#include <array>
1918
#include <vector>
2019

21-
#include "gmock/gmock.h"
2220
#include "gtest/gtest.h"
2321
#include "absl/base/config.h"
2422

@@ -47,4 +45,16 @@ TEST_F(LinearSearchTest, linear_searchConst) {
4745
absl::linear_search(const_container->begin(), const_container->end(), 4));
4846
}
4947

48+
#if defined(ABSL_INTERNAL_CPLUSPLUS_LANG) && \
49+
ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
50+
51+
TEST_F(LinearSearchTest, Constexpr) {
52+
static constexpr std::array<int, 3> kArray = {1, 2, 3};
53+
static_assert(absl::linear_search(kArray.begin(), kArray.end(), 3));
54+
static_assert(!absl::linear_search(kArray.begin(), kArray.end(), 4));
55+
}
56+
57+
#endif // defined(ABSL_INTERNAL_CPLUSPLUS_LANG) &&
58+
// ABSL_INTERNAL_CPLUSPLUS_LANG >= 202002L
59+
5060
} // namespace

0 commit comments

Comments
 (0)