47

Let's say I have an array of integers defined like that:

static constexpr int IntArray[] = {1, 5, 10, 12, 17};

Is there a way to get the minimum or maximum value at compile time?

2
  • 6
    It might be possible to do it with recursive constexpr functions. Commented Oct 27, 2016 at 13:16
  • In C++ it might be possible to use template meta-programming to solve it. Commented Oct 27, 2016 at 19:23

1 Answer 1

68

Let's get the C++17 solution out of the way for future search-landers:

constexpr int IntArray[] = {1, 5, 10, 12, 17};
constexpr int min = *std::min_element(std::begin(IntArray), std::end(IntArray));
static_assert(min == 1);

C++11 is more picky with constexpr functions, so we have to roll out a recursive algorithm. This one is a simple, linear one:

template <class T>
constexpr T &constexpr_min(T &a, T &b) {
    return a > b ? b : a;
}

template <class T>
constexpr T &arrayMin_impl(T *begin, T *end) {
    return begin + 1 == end
        ? *begin
        : constexpr_min(*begin, arrayMin_impl(begin + 1, end));
}

template <class T, std::size_t N>
constexpr T &arrayMin(T(&arr)[N]) {
    return arrayMin_impl(arr, arr + N);
}

constexpr int IntArray[] = {1, 5, 10, 12, 17};
constexpr int min = arrayMin(IntArray);

See it live on Coliru

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

11 Comments

Here I am manually trying to implement a c++17 version and there i already one. :( But good to know. ;)
This doesn't technically answer OPs question because you used a constexpr and not a static const
@AndyG I assumed that it is an oversight. A const array's contents are not compile-time constants, so if it isn't actually constexpr, nothing can be done at compile-time at all.
@Quentin: I wouldn't assume anything haha :-) I think the real answer is your second statement "Nothing can be done at compile-time at all"
@AndyG ...and would you then recommend not including the info about the constexpr case, which is actually useful?
|

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.