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

static operator()

Use case

Stateless function objects without object overhead.

Explanation

static operator() means no this pointer needed. This enables certain compiler optimizations. Also works for lambdas: []() static { ... }.

Code

#include <algorithm>
#include <cstdint>
#include <print>
#include <vector>

struct IsNop {
  static bool operator()(uint32_t opcode) {
    // $ echo "nop" | llvm-mc -arch=aarch64 -show-encoding
    // nop                                     // encoding: [0x1f,0x20,0x03,0xd5]
    return opcode == 0xD503201F;
  }
};

int main() {
  std::vector<uint32_t> opcodes = {
      0xD503201F,
      // $ echo "bl 0x40" | llvm-mc -arch=aarch64 -show-encoding
      // bl      #64                             // encoding: [0x10,0x00,0x00,0x94]
      0x94000010,
  };

  auto count = std::count_if(opcodes.begin(), opcodes.end(), IsNop{});
  std::println("NOP count: {}", count);

  return 0;
}

View on GitHub.

Output

$ ./src/c++23/build/static-call-operator
NOP count: 1