C++ for Embedded · Interview question

Can a template take something other than a type as a parameter?

A strong answer

Yes, templates can take non-type parameters, most usefully integral values. template <typename T, size_t N> class RingBuffer parameterizes both on element type T and on a compile-time capacity N, so RingBuffer<uint8_t, 64> has a T data_[N] array sized at compile time. This is exactly what makes templates ideal for embedded containers: the capacity is fixed at compile time, the storage is in-object (no heap, no fragmentation), and the size is known to the optimizer (so % N and bounds can be optimized). Each distinct value creates a distinct type and instantiation, though, RingBuffer<uint8_t,64> and RingBuffer<uint8_t,65> are two separate classes with separate code, which ties back to the code-bloat consideration. Non-type parameters can also be pointers/references in some forms, but compile-time integers for sizing are the common embedded use.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Templates: The Basics

Write a function or class once and have the compiler stamp out a type-specific version for each use: generic code with zero runtime cost, plus the code-bloat tradeoff to watch.

More Templates: The Basics questions

Browse all 472 interview questions