C++ for Embedded · Interview question

How do templates compare to C's approaches for generic code?

A strong answer

C has three options, all worse. A void*-based container (storage plus element size) loses type safety, it'll accept any pointer, and adds indirection and memcpy per element access. A macro that pastes a struct and functions per type has no real type checking, carries the preprocessor's double-evaluation and scoping hazards, and is painful to debug. Copy-pasting per type duplicates code that drifts out of sync. A C++ template gives one definition, full compile-time type checking (a RingBuffer<uint8_t> rejects an Event), and per-type optimized code with no indirection. The headline advantage is type safety with zero runtime cost: you can't accidentally push the wrong type, and there's no void* round-trip. The price, again, is code size per instantiation, but you gain correctness guarantees C simply can't express.

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
How do templates compare to C's approaches for generic code? | EmbeddedPrep.io