如何检查 const 数组成员在编译时单调增长

lom*_*omo 2 c++ constexpr constexpr-function

假设我们有 const 数组:

const int g_Values[] = { ... };
Run Code Online (Sandbox Code Playgroud)

如何检查成员在编译时单调增长,即g_Values[i] < g_Values[i + 1]

在运行时可以这样检查:

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;
}
Run Code Online (Sandbox Code Playgroud)

但如何用 constexpr 重写它并 if IsMonotonously()return false- 生成编译时错误。

fab*_*ian 5

对于仅 的数组来说这是不可能的const。您需要使其constexpr能够在 constexpr 上下文中使用它。

除此之外,您需要做的就是实现检查数组的函数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
Run Code Online (Sandbox Code Playgroud)