constexpr using standard library algorithms

Viewed 120

When built using C++17/C++20 x64 gcc/clang, the below snippet yields a compile error whereas de-referencing the iterator directly via *std::max_element(std::begin(arr), std::end(arr)) works fine. Any ideas as to why? I've also observed similar behavior with other standard algorithms that have become constexpr since C++20, e.g. std::upper_bound

int main()
{
    constexpr std::array<int,5> arr = {1,2,3,4,5};
    constexpr auto it = std::max_element(std::begin(arr), std::end(arr));
}
source>:11:73: error: '(((std::array<int, 5>::const_pointer)(& arr.std::array<int, 5>::_M_elems)) + 16)' is not a constant expression
   11 |     constexpr auto it  = std::max_element(std::begin(arr), std::end(arr));
      |           
1 Answers

it has to store a pointer to the element of arr.

Since arr is not static, it's located on the stack, so its address can't be determined at compile-time.

It will work if you make arr static.

Related