Ежедневный бит (е) C ++ # 38, вариант C ++ 23 if: if consteval {}

В C++23 добавлен оператор if consteval {} с возможностью проверки, является ли код вычисляемым константой.

Это полезно, чтобы различать альтернативные реализации или учитывать побочные эффекты во время выполнения, такие как мониторинг.

constexpr int add(int a, int b) {
    if consteval {
        // consteval branch that can only use 
        // constant expression compatible code
        return a + b;
    } else {
        // not consteval, we can use fancy things 
        // like inline assembler, or intristics
        int ret;
        asm("addl %%ebx, %%eax;":"=a"(ret) : "a"(a), "b"(b));
        return ret;
    }
}

constexpr int side(int arg) {
    // Useful for side-effects such as logging...
    if !consteval {
        std::cout << "Not a constant expression, we can safely log.\n";
    }
    return arg*arg;
}

Откройте пример в Compiler Explorer.