2

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));
      |           
2
  • So the problem seems to be if std::begin/ std::end are constexpr, fed with a constexpr std::array, and std::max_element is constexpr, why can't std::max_element's output be constexpr too? Commented Dec 27, 2020 at 9:13
  • 1
    Particularly given that *std:max_element output IS constexpr Commented Dec 27, 2020 at 9:15

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, given*std::max_element works, presumably it treats obtaining the iterator and de-referencing it as a single monolithic expression that itself can be constexpr.
@user3882729 I'm not sure I'd say that. The std::max_element call is something that can be evaluated at compile-time, "on it's own". But the value resulting from that evaluation is subject to further tests when you try to use it to initialize a constexpr variable. The iterator, which has &arr "in" it does not pass unless arr is static, but the dereferenced value is atomic and does pass. The iterator "is constexpr" in the sense that it's allowed as an intermediate in constexpr computation, just not as the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.