user3882729
user3882729

Reputation: 1534

constexpr using standard library algorithms

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));
      |           

Upvotes: 2

Views: 239

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96043

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.

Upvotes: 7

Related Questions