Writing compile-time prime detection in C++ templates
This hard C++ problem tests whether you can leverage template metaprogramming to perform computation at compile time rather than runtime. High-frequency trading firms routinely use compile-time computation to eliminate latency-sensitive runtime work, and this question directly probes that skill.
The challenge is to design a template structure that evaluates primality during the compilation phase, producing a compile-time constant that the linker can optimize away entirely. You'll need to reason about template specialization, recursive instantiation, and how the compiler unrolls template logic into constant expressions.
- Template specialization (full and partial)
- Compile-time recursion and template depth
- Constant expression evaluation and
constexpr semantics - Integer arithmetic within template parameters
Strong solutions avoid runtime branches altogether and allow the compiler to fold the entire computation into a single constant at link time, leaving zero overhead in the generated binary.