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

constexpr if

Use case

Compile-time branching for 32/64-bit handling.

Explanation

if constexpr evaluates at compile-time.

Code

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

template <typename T> void printAddr(T addr) {
  if constexpr (sizeof(T) == 8) {
    std::cout << "64-bit: 0x" << std::hex << addr << "\n";
  } else {
    std::cout << "32-bit: 0x" << std::hex << addr << "\n";
  }
}

int main() {
  printAddr(uint64_t{0x10001000});
  printAddr(uint32_t{0x1000});
  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/constexpr-if
64-bit: 0x10001000
32-bit: 0x1000