Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::is_constant_evaluated

Use case

Different code paths for compile-time and runtime.

Explanation

std::is_constant_evaluated returns true during constant evaluation. Enables different implementation for compile-time vs runtime.

Code

#include <cstdint>
#include <iostream>
#include <type_traits>

// https://en.wikipedia.org/wiki/Mach-O
constexpr bool isMachO(uint32_t magic) {
  if (std::is_constant_evaluated()) {
    return magic == 0xFEEDFACF || magic == 0xFEEDFACE;
  } else {
    std::cout << "Checking magic at runtime.\n";
    return magic == 0xFEEDFACF || magic == 0xFEEDFACE;
  }
}

int main() {
  constexpr bool a = isMachO(0xFEEDFACF);
  bool b = isMachO(0xFEEDFACF);

  std::cout << "a: " << std::boolalpha << a << ", b: " << b << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/std-is_constant_evaluated
Checking magic at runtime.
a: true, b: true