constexpr all the things in irange.h (#147633)

I got complaints while irangeifying some files in ExecuTorch
that irange could not be used in a constexpr function. This made the
complaints go away.

I added a constexpr function in irange_test that used to fail to build
with `error: variable of non-literal type 'iterator' (aka
'integer_iterator<int, true>') cannot be defined in a constexpr
function before C++23` and now builds fine.

Differential Revision: [D69959614](https://our.internmc.facebook.com/intern/diff/D69959614/)
Pull Request resolved: https://github.com/pytorch/pytorch/pull/147633
Approved by: https://github.com/albanD
This commit is contained in:
Scott Wolchok
2025-02-21 10:41:22 -08:00
committed by PyTorch MergeBot
parent 6e0b09728a
commit 84fcf1bb11
2 changed files with 42 additions and 12 deletions

View File

@@ -4,6 +4,8 @@
#include <gtest/gtest.h>
#include <array>
using namespace ::testing;
TEST(irangeTest, range_test) {
@@ -56,3 +58,31 @@ TEST(irange, empty_reverse_range_one_input) {
const std::vector<int> correct = {};
ASSERT_EQ(test_vec, correct);
}
constexpr std::array<int, 3> toy_iota() {
std::array<int, 3> result = {0};
for (const auto i : c10::irange(3)) {
result[i] = i;
}
return result;
}
constexpr std::array<int, 3> toy_iota_with_start(int start) {
std::array<int, 3> result = {0};
for (const auto i : c10::irange(start, start + 3)) {
result[i - start] = i;
}
return result;
}
TEST(irange, constexpr_ok) {
constexpr auto arr = toy_iota();
static_assert(arr[0] == 0);
static_assert(arr[1] == 1);
static_assert(arr[2] == 2);
constexpr auto arr2 = toy_iota_with_start(4);
static_assert(arr2[0] == 4);
static_assert(arr2[1] == 5);
static_assert(arr2[2] == 6);
}