[libcxx-commits] [libcxx] [libc++][test] Refactor tests for ranges::swap_range algorithms (PR #121138)

Peng Liu via libcxx-commits libcxx-commits at lists.llvm.org
Fri Feb 21 13:35:25 PST 2025


================
@@ -51,72 +47,115 @@ auto can_swap_test(...) -> std::false_type;
 
 template <class Tp>
 constexpr bool can_swap() {
-    return std::is_same<decltype(can_swap_test<Tp>(0)), void>::value;
+  return std::is_same<decltype(can_swap_test<Tp>(0)), void>::value;
 }
 #endif
 
-#if TEST_STD_VER > 17
-constexpr bool test_swap_constexpr()
-{
+#if TEST_STD_VER >= 11
+// This test is constexpr only since C++23 because constexpr std::unique_ptr is only available since C++23
+TEST_CONSTEXPR_CXX23 bool test_unique_ptr() {
----------------
winner245 wrote:

I tried to inline `test_unique_ptr()` into `test()`, but encountered a `[stage2 (generic-cxx20, clang-21, clang++-21)](https://github.com/llvm/llvm-project/actions/runs/13449074444/job/37621070195?pr=121138#logs)` CI failure. The issue arises because the top-level `test()` is constexpr since C++20 (declared via `TEST_CONSTEXPR_CXX20`), while `unique_ptr` is constexpr since C++23. Thus, inlining the code involving `unique_ptr` directly inside `test()` results in an error: `variable of non-literal type 'std::unique_ptr<int>' cannot be defined in a constexpr function before C++23`.

```cpp
TEST_CONSTEXPR_CXX20 bool test() { 
  // error: variable of non-literal type 'std::unique_ptr<int>' cannot be defined in a constexpr function before C++23
  if (TEST_STD_VER >= 23 || !TEST_IS_CONSTANT_EVALUATED)
    std::unique_ptr<int> p(new int); 

  return true;
}
```

A reproducer of this problem is avaialble: https://godbolt.org/z/Kzn96GEM9

To resolve this, I moved the test for `unique_ptr` into a separate function, `test_unique_ptr()`, which can be declared with `TEST_CONSTEXPR_CXX23`. Then, within `test()`, I used the suggested `TEST_IS_CONSTANT_EVALUATED` trick:

```cpp
TEST_CONSTEXPR_CXX23 void test_unique_ptr() {
  std::unique_ptr<int> p(new int);
}
 
TEST_CONSTEXPR_CXX20 bool test() { 
  if (TEST_STD_VER >= 23 || !std::__libcpp_is_constant_evaluated())
    test_unique_ptr();

  return true;
}
```

This resolves the CI failure. I am not sure if there is a better way to resolve this. I found reverting to the `test_unique_ptr()` function a simple fix. 

https://github.com/llvm/llvm-project/pull/121138


More information about the libcxx-commits mailing list