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

Class types in non-type template parameters

Use case

Use structs as template parameters.

Explanation

Structs with only public members, no pointers and constexpr-compatible types can be NTTP. Keeps related values together (mask + value) instead of separate template params. Compiler fully inlines (no runtime overhead).

Code

#include <cstdint>
#include <iostream>

struct Opcode {
  uint32_t mask;
  uint32_t value;
};

template <Opcode op> bool matches(uint32_t instr) {
  return (instr & op.mask) == op.value;
}

int main() {
  // https://developer.arm.com/documentation/ddi0602/2025-12/Base-Instructions/BL--Branch-with-link-?lang=en
  constexpr Opcode BL{0xFC000000, 0x94000000};

  // $ echo "bl 0x40" | llvm-mc -triple=aarch64 -show-encoding
  // bl	#64                             // encoding: [0x10,0x00,0x00,0x94]
  uint32_t instr = 0x94000010;

  if (matches<BL>(instr)) {
    std::cout << "Matched BL." << "\n";
  }

  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/class-types-in-non-type-template-parameters
Matched BL.