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

Non-type template parameters with auto

Use case

Compile-time buffer sizes with any constant type.

Explanation

auto lets one template accept any constant type (int, unsigned, char etc.). Before C++17, we would need template<int N> or template<size_t N> (separate templates for each type).

Code

#include <cstdint>
#include <iostream>

template <auto N> struct Buffer {
  uint8_t data[N];
  static constexpr auto size = N;
};

int main() {
  Buffer<64> small;
  Buffer<0x1000> page;

  std::cout << "Small: " << small.size << "\n";
  std::cout << "Page: 0x" << std::hex << page.size << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/non-type-template-parameters-with-auto
Small: 64
Page: 0x1000