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

Variadic templates

Use case

Generic hook wrapper that intercepts calls with any number of arguments.

Explanation

typename... Args declares a parameter pack that captures zero or more types. Args... args captures the actual arguments. args... is used to expand them.

Code

#include <cstdint>
#include <iostream>

void readMemory(uint64_t addr) {
  std::cout << "addr=0x" << std::hex << addr << "\n";
}

void readMemory(uint64_t addr, size_t len) {
  std::cout << "addr=0x" << std::hex << addr << " len=0x" << std::hex << len
            << "\n";
}

template <typename... Args> void hookWrapper(const char *name, Args... args) {
  std::cout << "Calling " << name << " (" << sizeof...(args) << " args).\n";

  readMemory(args...);
}

int main() {
  hookWrapper("readMemory", 0x10001000);
  hookWrapper("readMemory", 0x10001000, 0x100);

  return 0;
}

View on GitHub.

Output

$ ./src/c++11/build/variadic-templates
Calling readMemory (1 args).
addr=0x10001000
Calling readMemory (2 args).
addr=0x10001000 len=0x100