Explain templates in C++ and provide a simple example.
Show answer and explanation
Templates parameterize functions, classes, aliases, or variables over types, values, and in some cases other templates. The compiler forms specializations when they are needed, enabling zero-overhead generic code but potentially increasing compile time and generated code size. C++20 concepts can state requirements explicitly and improve overload selection and diagnostics compared with unconstrained substitution failures.
Templates parameterize functions, classes, aliases, or variables over types, values, and in some cases other templates. The compiler forms specializations when they are needed, enabling zero-overhead generic code but potentially increasing compile time and generated code size. C++20 concepts can state requirements explicitly and improve overload selection and diagnostics compared with unconstrained substitution failures.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.