Templates in C++


Templates in C++ Interview with follow-up questions

1. What are templates in C++ and why are they used?

Templates in C++ are a compile-time mechanism for writing generic, type-independent code. The compiler generates a concrete instantiation for each unique set of template arguments — this is called template instantiation. There are two primary kinds:

  • Function templates — generic functions that work across types (e.g., std::max, std::swap)
  • Class templates — generic classes that parameterize one or more types (e.g., std::vector, std::optional)

Templates are used because they enable zero-overhead abstraction: the genericity is resolved entirely at compile time, so there is no runtime cost from virtual dispatch or type erasure.

C++20 extended templates significantly with Concepts, which allow you to constrain template parameters and get clear compiler errors when constraints are violated:

template 
concept Numeric = std::integral || std::floating_point;

template 
T square(T x) { return x * x; }

Without Concepts (pre-C++20), a type mismatch in a template produced notoriously unreadable error messages deep inside the instantiation chain. Concepts surface the error at the call site with a human-readable diagnostic.

Common follow-up: "What is the difference between templates and macros?" — Templates are type-safe and scoped; macros are textual substitution with no type checking. Templates should always be preferred for generic code.

↑ Back to top

Follow-up 1

Can you explain the difference between function templates and class templates?

In C++, function templates are used to define generic functions that can work with different types of data. The function template is defined using the 'template' keyword followed by the template parameter list and the function signature. The template parameter list specifies one or more type parameters that can be used within the function.

Class templates, on the other hand, are used to define generic classes. The class template is defined using the 'template' keyword followed by the template parameter list and the class definition. The template parameter list specifies one or more type parameters that can be used within the class definition. Class templates can be used to create multiple instances of a class, each with a different data type.

Follow-up 2

How do you define a template function in C++?

To define a template function in C++, you need to use the 'template' keyword followed by the template parameter list and the function signature. The template parameter list specifies one or more type parameters that can be used within the function. Here's an example of a template function that swaps two values:

// Template function to swap two values

template 
void swap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}

In this example, the 'typename' keyword is used to specify the type parameter. The function can then be called with different types of data, and the compiler will generate the appropriate code for each type.

Follow-up 3

What is template specialization in C++?

Template specialization in C++ allows you to provide a different implementation for a template function or class for a specific type or set of types. It allows you to customize the behavior of a template for certain types, while still using the generic template for other types.

Here's an example of template specialization for a function template:

// Generic template function

template 
void print(T value) {
    std::cout << value << std::endl;
}

// Template specialization for int

template <>
void print(int value) {
    std::cout << "Specialized: " << value << std::endl;
}

In this example, the generic template function 'print' can be used with any type. However, a specialized version of the function is provided for the 'int' type. When the function is called with an 'int' argument, the specialized version will be used instead of the generic version.

Follow-up 4

Can you provide an example of a template class in C++?

Certainly! Here's an example of a template class in C++:

// Template class for a generic stack

template 
class Stack {
private:
    std::vector data;
public:
    void push(T value) {
        data.push_back(value);
    }
    T pop() {
        T value = data.back();
        data.pop_back();
        return value;
    }
    bool empty() {
        return data.empty();
    }
};

In this example, the 'Stack' class is defined as a template class with a single type parameter 'T'. This allows the class to be used with different types of data. The class provides methods to push and pop values from the stack, as well as check if the stack is empty. The actual implementation of the class will be generated by the compiler when the class is used with a specific type.

2. What is the syntax to declare a template function in C++?

The basic syntax for a template function uses the template keyword followed by a template parameter list:

template 
T add(T a, T b) {
    return a + b;
}

typename and class are interchangeable in this position. You can also have multiple type parameters, non-type parameters (e.g., integers), and template template parameters:

// Multiple type parameters
template 
auto multiply(T a, U b) -> decltype(a * b) {
    return a * b;
}

// Non-type template parameter
template 
T sum(const std::array& arr) {
    T total{};
    for (const auto& v : arr) total += v;
    return total;
}

C++20 abbreviated function templates provide a cleaner syntax using auto parameters — each auto parameter implicitly introduces a template type parameter:

// Equivalent to template 
auto add(auto a, auto b) {
    return a + b;
}

C++20 Concepts let you constrain template parameters directly in the declaration:

#include 

template 
T factorial(T n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}

The compiler instantiates a separate version of the function for each unique set of argument types it encounters at compile time.

↑ Back to top

Follow-up 1

Can you provide an example of a template function?

Sure! Here's an example of a template function that swaps two values:

template 
void swap(T& a, T& b)
{
    T temp = a;
    a = b;
    b = temp;
}

Follow-up 2

What happens if we don't include the template <typename T> line while declaring a template function?

If we don't include the template line while declaring a template function, the compiler will treat the function as a regular non-template function. This means that the function will only work with a specific type, and not be able to handle different types dynamically.

Follow-up 3

Can we have more than one generic type in a template function?

Yes, we can have more than one generic type in a template function. We can use multiple template parameters separated by commas. Here's an example:

template 
void printPair(T first, U second)
{
    std::cout &lt;&lt; first &lt;&lt; " " &lt;&lt; second &lt;&lt; std::endl;
}

3. What is a template class in C++ and how is it different from a regular class?

A template class (or class template) is a blueprint for generating a family of classes parameterized by one or more types. A regular class is a fixed blueprint for a single concrete type.

// Regular class — works only with int
class IntBox {
    int value;
public:
    IntBox(int v) : value(v) {}
    int get() const { return value; }
};

// Class template — works with any type T
template 
class Box {
    T value;
public:
    Box(T v) : value(std::move(v)) {}
    T get() const { return value; }
};

Box    intBox{42};
Box strBox{"hello"};

Key differences:

Regular class Template class
Type Fixed at definition Supplied by caller
Instantiation Once Once per unique argument set
Defined in .cpp or header Header only (by default)
Type errors At compile time At instantiation time

C++20 Concepts can constrain template class parameters so that only types meeting certain requirements are accepted:

template 
class SafeBox {
    T value;
public:
    explicit SafeBox(T v) : value(std::move(v)) {}
    T get() const { return value; }
};

Important gotcha interviewers probe: template class definitions must generally be visible in every translation unit that instantiates them — you cannot put the implementation in a .cpp file the same way you can for regular classes. The full definition goes in the header (or an .tpp/.ipp file included by the header). C++20 modules address this limitation by allowing template definitions to be exported from a module interface unit.

↑ Back to top

Follow-up 1

Can you provide an example of a template class?

Sure! Here's an example of a template class in C++:

#include 

// Template class definition

template 
class MyTemplateClass {
public:
    MyTemplateClass(T value) : data(value) {}
    void printData() {
        std::cout &lt;&lt; "Data: " &lt;&lt; data &lt;&lt; std::endl;
    }
private:
    T data;
};

int main() {
    // Creating objects of the template class
    MyTemplateClass obj1(10);
    MyTemplateClass obj2("Hello");

    // Calling member functions
    obj1.printData();
    obj2.printData();

    return 0;
}

In this example, MyTemplateClass is a template class that can work with different types. We create objects of the template class using different types (int and std::string) and call the printData member function to display the data stored in each object.

Follow-up 2

How can we create objects of a template class?

To create objects of a template class, we need to specify the actual types for the template parameters. This can be done by providing the type(s) inside angle brackets (&lt;&gt;) after the template class name. For example, if we have a template class MyTemplateClass with a single template parameter, we can create objects of this class as follows:

MyTemplateClass obj1(10); // Creating an object with int as the template parameter
MyTemplateClass obj2("Hello"); // Creating an object with std::string as the template parameter

In the above example, obj1 is an object of MyTemplateClass with int as the template parameter, and obj2 is an object of MyTemplateClass with std::string as the template parameter.

Follow-up 3

What is the use of template parameters in a template class?

Template parameters in a template class are used as placeholders for different types. They allow the template class to be generic and work with multiple types without the need to rewrite the code for each specific type. Template parameters can be used to define the type of member variables, function parameters, and return types within the template class. They can also be used to specify the types of objects to be created when creating instances of the template class.

For example, in the template class MyTemplateClass, the template parameter T is used to define the type of the data member variable and the type of the constructor parameter. It is also used as the return type of the printData member function.

4. What is template specialization in C++?

Template specialization lets you provide a custom implementation of a template for a specific type or set of types, overriding the general (primary) template.

There are two kinds:

1. Full (explicit) specialization — specializes for one exact type:

// Primary template
template 
struct Serializer {
    static std::string serialize(const T&amp; val) {
        return std::to_string(val);
    }
};

// Full specialization for bool
template &lt;&gt;
struct Serializer {
    static std::string serialize(bool val) {
        return val ? "true" : "false";
    }
};

2. Partial specialization — specializes for a subset of possible arguments (only valid for class/variable templates, not function templates):

// Partial specialization: pointer types
template 
struct Serializer {
    static std::string serialize(T* ptr) {
        return ptr ? Serializer::serialize(*ptr) : "null";
    }
};

C++20 context: Many use cases that previously required specialization can now be handled more cleanly with if constexpr or Concepts:

template 
std::string serialize(const T&amp; val) {
    if constexpr (std::is_same_v)
        return val ? "true" : "false";
    else
        return std::to_string(val);
}

Common interview follow-up: "Can you partially specialize a function template?" — No. Partial specialization is only available for class and variable templates. For functions, use overloading or if constexpr instead.

↑ Back to top

Follow-up 1

Can you provide an example of template specialization?

Sure! Here's an example of template specialization:

// Generic template

template 
void print(T value) {
    std::cout &lt;&lt; "Generic template: " &lt;&lt; value &lt;&lt; std::endl;
}

// Specialization for int

template &lt;&gt;
void print(int value) {
    std::cout &lt;&lt; "Specialization for int: " &lt;&lt; value &lt;&lt; std::endl;
}

int main() {
    print(10); // Calls the specialized version
    print(3.14); // Calls the generic version
    return 0;
}

In this example, we have a generic template function print that prints a value. We then provide a specialization for the int type, which prints a different message. When we call print(10), it will use the specialized version, and when we call print(3.14), it will use the generic version.

Follow-up 2

Why is template specialization needed?

Template specialization is needed in C++ when you want to provide a different implementation for a template based on specific types or values. It allows you to customize the behavior of a template for certain cases. This can be useful when you need to handle specific types differently or optimize the code for certain values.

Follow-up 3

What is the difference between full specialization and partial specialization?

In C++, there are two types of template specialization: full specialization and partial specialization.

  • Full specialization: In full specialization, you provide a complete implementation for a template when specific template arguments are used. This means that the specialized version completely replaces the generic version for those specific arguments.

  • Partial specialization: In partial specialization, you provide a more specific implementation for a template when a subset of template arguments is used. The generic version is still used for other arguments that do not match the specialized version.

In other words, full specialization provides a complete replacement for the generic template, while partial specialization provides a more specific implementation for a subset of template arguments.

5. What are the advantages and disadvantages of using templates in C++?

Templates in C++ provide a powerful mechanism for generic programming. The main advantages of using templates are:

  1. Code Reusability: A single template definition works with many types, eliminating redundant implementations (e.g., std::vector replaces separate IntVector, DoubleVector, etc.).

  2. Type Safety: All type checking happens at compile time. Invalid usage is caught before the program runs, unlike runtime-polymorphism approaches.

  3. Zero Runtime Overhead: The compiler generates specialized code for each instantiation, so there is no virtual dispatch, type erasure, or boxing cost at runtime.

  4. Expressiveness with C++20 Concepts: Concepts constrain template parameters and produce readable compile-time errors, making template interfaces self-documenting.

The main disadvantages are:

  1. Code Bloat: Each instantiation produces its own copy of compiled code. A template used with many types increases binary size. Link-time optimization (LTO) can mitigate this.

  2. Increased Compilation Time: Templates are resolved by the compiler, not the linker, so each translation unit that uses a template must parse and instantiate it. Heavy template use can dramatically slow builds. C++20 modules reduce this by caching compiled module interfaces.

  3. Error Messages: Before Concepts, template errors produced long, deeply nested diagnostics. Concepts (C++20) surface errors at the call site with clear constraint-violation messages.

  4. Implementation in Headers: Template definitions must typically be visible at the point of instantiation, so they cannot be hidden in .cpp files the same way regular functions can. C++20 modules address this for module-based codebases.

↑ Back to top

Follow-up 1

Can templates lead to code bloat?

Yes, templates can lead to code bloat. Each instantiation of a template with a different type generates a separate copy of the code. This can result in larger executable sizes and increased memory usage. To mitigate code bloat, techniques like explicit template instantiation and template specialization can be used.

Follow-up 2

How can templates improve performance?

Templates can improve performance in several ways:

  1. Code Specialization: Templates allow the compiler to generate specialized code for each type used, optimizing the code for specific data types. This can result in faster execution compared to generic code.

  2. Inlining: Templates enable the compiler to inline function calls, eliminating the overhead of function calls and improving performance.

  3. Compile-time Optimization: Templates perform compile-time computations, allowing the compiler to optimize the code based on the template parameters. This can lead to more efficient code execution.

By leveraging these performance benefits, templates can help in writing efficient and optimized code.

Follow-up 3

What are some common pitfalls when using templates in C++?

When using templates in C++, there are some common pitfalls to be aware of:

  1. Name Lookup: Templates can have complex name lookup rules, which can lead to unexpected behavior or compilation errors.

  2. Template Instantiation: Template code is only instantiated when it is used, which can result in compilation errors if the template code is not used correctly.

  3. Template Metaprogramming: Template metaprogramming can be powerful but also complex. It can lead to hard-to-understand code and increased compilation times.

  4. Template Syntax: Templates have their own syntax, which can be challenging to understand and use correctly.

  5. Code Readability: Templates can make the code more difficult to read and understand, especially when used with complex type deductions or template metaprogramming techniques.

To avoid these pitfalls, it is important to have a good understanding of template syntax and usage, and to carefully test and validate template code.

Live mock interview

Mock interview: Templates in C++

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.