Autocoder

C++ Templates Interview Questions

Last updated 2026-11-19

Templates are how C++ achieves generic programming without run-time cost, and they are a favourite topic for experienced-candidate interviews. The questions range from "why are templates defined in headers" to writing a variadic sum or constraining a function with a concept.

Each answer below explains what the compiler does: it instantiates a separate function or class for every distinct set of template arguments, checking the code only then. That one fact explains the error messages, the header-only rule and the code-size trade-off. For containers built on templates see C++ STL questions; for dynamic alternatives see virtual functions.

CoversFunction and class templates, specialisation, SFINAE, concepts
StandardC++11 to C++20
LevelMedium to hard

Key vocabulary

How to structure an answer

State the mechanism first, then a three-line example, then the pitfall. For example, on specialisation: describe the primary template, show a full specialisation for bool, and mention that function templates cannot be partially specialised, so you overload instead.

C++ Templates Interview Questions: questions with worked answers

  1. 1

    What is a template and how does it differ from a macro?

    easy

    A template is a parameterised definition from which the compiler generates type-safe functions or classes. Unlike a macro, which is textual substitution done before parsing, a template is understood by the compiler: it respects scope, is type-checked on instantiation, can be specialised and overloaded, and does not evaluate its arguments twice. A macro MAX(a, b) evaluates the larger argument twice, so MAX(i++, j) misbehaves; std::max does not.

  2. 2

    Why are template definitions usually placed in header files?

    easy

    The compiler needs the full definition at the point of instantiation, in each translation unit that uses a particular instantiation. If the definition is in a .cpp file, the other translation units see only a declaration and the linker finds no instantiation, producing "undefined reference" errors. Put the definition in the header, or explicitly instantiate known types in the .cpp with "template class Foo<int>;". The inline-by-default nature of templates means duplicates across translation units are permitted by the one-definition rule.

  3. 3

    How does template argument deduction work? Predict the result.

    medium

    Deduction compares the parameter type pattern with the argument type and ignores top-level const and references for by-value parameters. With T by value, f(x) where x is const int& deduces T as int. With T&& (a forwarding reference) and an lvalue argument, T is deduced as an lvalue reference and reference collapsing yields int&. Conflicting deductions from two arguments are an error: max(1, 2.5) fails for template<class T> T max(T, T) because T would be int and double.

    cpp
    template <class T> void by_val(T) {}
    template <class T> void fwd(T&&) {}
    const int x = 1;
    by_val(x);   // T = int
    fwd(x);      // T = const int&
    fwd(5);      // T = int, parameter is int&&
  4. 4

    What is template specialisation, and why can you not partially specialise a function template?

    medium

    A full specialisation provides a different implementation for exact arguments, and a partial specialisation (classes and variable templates only) for a family of arguments such as T*. Function templates cannot be partially specialised because overloading already handles that case and the two mechanisms would interact confusingly: overload resolution ignores specialisations, picking among primary templates first. The idiom is to overload the function, or delegate to a class template that can be partially specialised.

    cpp
    template <class T> struct Name { static const char* get() { return "other"; } };
    template <> struct Name<int> { static const char* get() { return "int"; } };
    template <class T> struct Name<T*> { static const char* get() { return "pointer"; } };
  5. 5

    Write a variadic function that sums its arguments, in C++11 and C++17.

    medium

    Variadic templates accept any number of arguments through a parameter pack. C++11 uses recursion with a base case; C++17 fold expressions do it in one line. The pack is expanded with "...". sizeof...(args) gives the number of arguments without evaluating them.

    cpp
    // C++11
    template <class T> T sum(T a) { return a; }
    template <class T, class... R> T sum(T a, R... rest) { return a + sum(rest...); }
    // C++17
    template <class... T> auto sum17(T... a) { return (a + ...); }
    // sum17(1, 2, 3) == 6
  6. 6

    What is SFINAE? Give an example.

    hard

    Substitution Failure Is Not An Error: when the compiler substitutes deduced types into a function template signature and that produces an invalid type, the template is dropped from the overload set rather than causing a compile error. It is used to enable a function only for certain types, via std::enable_if or decltype tricks. Since C++20, concepts and requires clauses express the same intent with far better diagnostics.

    cpp
    template <class T>
    std::enable_if_t<std::is_integral_v<T>, T> half(T x) { return x / 2; }
    template <class T>
    std::enable_if_t<std::is_floating_point_v<T>, T> half(T x) { return x * 0.5; }
  7. 7

    What are C++20 concepts and how do they improve on SFINAE?

    medium

    A concept is a named compile-time predicate on template arguments, and a requires clause or constrained parameter uses it to restrict a template. Violations produce a short message naming the failed requirement instead of pages of substitution errors, constraints take part in overload ranking (more constrained wins) and the code reads like documentation.

    cpp
    template <class T> concept Number = std::is_arithmetic_v<T>;
    template <Number T> T twice(T x) { return x + x; }
    auto g(std::integral auto n) { return n * 2; }
    // twice("a") -> error: constraint Number not satisfied
  8. 8

    What is the difference between typename and class in a template parameter, and when is typename required elsewhere?

    medium

    In the parameter list they are interchangeable. Elsewhere, typename is required to tell the compiler that a dependent name, one that depends on a template parameter, names a type, as in typename T::value_type. Without it the compiler assumes the name is a value. In C++20 the keyword is optional in many contexts such as alias declarations and return types, but still needed in a plain declaration inside a function body.

  9. 9

    What is perfect forwarding and how does std::forward work?

    hard

    Perfect forwarding passes arguments to another function preserving their value category: lvalues stay lvalues, rvalues stay rvalues. A parameter of type T&& in a deduced context is a forwarding reference. Inside the function the name is always an lvalue, so std::forward<T>(arg) casts it back to an rvalue only if the argument was originally an rvalue. make_unique and emplace_back rely on it. Using std::move instead would wrongly steal from lvalues.

    cpp
    template <class T, class... A>
    std::unique_ptr<T> make(A&&... a) {
        return std::unique_ptr<T>(new T(std::forward<A>(a)...));
    }
  10. 10

    What are non-type template parameters? Write a fixed-size array class.

    medium

    Besides types, templates can take compile-time values: integers, enums, pointers and (C++20) literal class types. They let the size be part of the type, so the compiler can unroll and check at compile time, as std::array<int, 5> does. Different sizes are different types, so std::array<int,3> and std::array<int,4> are unrelated and cause separate instantiations.

    cpp
    template <class T, size_t N>
    struct Arr {
        T data[N];
        constexpr size_t size() const { return N; }
        T& operator[](size_t i) { return data[i]; }
    };
    Arr<int, 4> a{};
  11. 11

    What is class template argument deduction (CTAD) in C++17?

    medium

    It lets the compiler deduce a class template's arguments from the constructor call, so std::pair p(1, 2.5) deduces pair<int,double> and std::vector v{1,2,3} deduces vector<int>. For your own types, deduction comes from constructors or from explicit deduction guides. A common surprise: std::vector v{std::vector{1,2}} produces vector<int> copy, not vector<vector<int>>, because the copy deduction candidate wins.

  12. 12

    What does if constexpr do?

    hard

    In a template, if constexpr evaluates its condition at compile time and discards the false branch entirely, so the discarded code need not compile for that instantiation. A normal if still requires both branches to be valid for every type. It replaces many SFINAE overload sets with a single readable function.

    cpp
    template <class T> std::string str(T v) {
        if constexpr (std::is_arithmetic_v<T>) return std::to_string(v);
        else return std::string(v);   // only compiled for non-arithmetic T
    }
  13. 13

    What is code bloat in templates and how do you limit it?

    medium

    Each distinct instantiation generates its own machine code, so many types or large functions grow the binary and slow the build. Mitigations: move type-independent code into a non-template base or helper, instantiate explicitly and keep the definition in a .cpp (extern template), let the linker fold identical code, and avoid needless instantiations such as using int and long where one suffices. Compile times usually matter more than size in practice.

Frequently asked questions

Are templates evaluated at compile time or run time?

Instantiation is entirely compile time. Whatever code the instantiation contains then runs at run time, unless it is constexpr.

What is the difference between templates and generics in Java?

C++ templates generate separate code per type and work with primitives and values. Java generics use type erasure with one compiled version. See Java collections questions for the Java side.

Do I need to know template metaprogramming for interviews?

Most service-company interviews stop at function and class templates and specialisation. Product and systems roles may ask SFINAE, concepts and perfect forwarding.

Where do concepts fit in?

They replace SFINAE for new code in C++20 with clearer errors. Know both, since older code bases use enable_if widely.

Related guides

More in Programming Language Interview Questions by Language

See all in this section