c++constexprconstexpr-function

how to check that const array members grow monotonically at compile time


assume we have const array:

const int g_Values[] = { ... };

how check that members grow monotonically at compile time, i.e. g_Values[i] < g_Values[i + 1]

in runtime this possible to check like this:

bool IsMonotonously()
{
    int i = _countof(g_Values);
    int m = MAXINT;
    do 
    {
        int v = g_Values[--i];
        if (v >= m) return false;
        m = v;
    } while (i);
    return true;
}

but how rewrite this with constexpr and if IsMonotonously() return false - generate compile time error.


Solution

  • This is impossible for an array that is just const. You need to make it constexpr to be able to use it in a constexpr context.

    All you need to do in addition to this is to implement the function for checking the array as constexpr:

    template<class T, size_t N>
    constexpr bool IsStrictlyMonotonouslyIncreasing(T (&arr)[N])
    {
        bool result = true;
    
        if (N > 1)
        {
            for (size_t i = 0; result && (i != N - 1); ++i)
            {
                result = (arr[i] < arr[i + 1]);
            }
        }
    
        return result;
    }
    
    const int g_Values[] = { 1, 2, 3, 4 };
    static_assert(IsStrictlyMonotonouslyIncreasing(g_Values)); // compiler error g_Values is not usable in a constexpr context
    
    constexpr int g_Values2[] = { 1, 2, 3, 4 };
    static_assert(IsStrictlyMonotonouslyIncreasing(g_Values2)); // ok