CodeBlanks Logo Icon CodeBlanks

template<typename T>

Learn to write generic functions with template<typename T>.

What is a template?

A template lets you write type-independent code. The template <typename T> declaration introduces a type parameter named T. The compiler generates a separate version for each type used.

Example: template <typename T> T identity(T x) { return x; } works for int, double and std::string. When you call identity(42), the compiler generates a version with T=int. This is called instantiation.

Type deduction

You don't have to specify the type when calling a template function. In identity(42) the compiler deduces T=int (type deduction). This keeps code concise.

You can also specify the type explicitly: identity<double>(3.14). This is needed when deduction would be ambiguous. For example, identity(3.14) deduces T=double. Templates spare you from writing the same function for many types.

Practice Write the identity template

Write template <typename T> T identity(T x) that returns x. In main call std::cout << identity(42) << std::endl;.

Starter code

main.cpp
#include <iostream>

// write the identity template function: T identity(T x)

int main() {
    // call identity and print the result
    return 0;
}

Sample solution

main.cpp
#include <iostream>

template <typename T>
T identity(T x) {
    return x;
}

int main() {
    std::cout << identity(42) << std::endl;
    return 0;
}

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which keyword declares a type parameter?

main.cpp
template <___> T identity(T x);
  • typename Correct answer
  • typedef
  • auto
  • static

Explanation: typename declares a type parameter. class can be used the same way.

2 Complete the template declaration

Question
template <____> T identity(T x) { return x; }
Answer
template <typename T> T identity(T x) { return x; }

Explanation: template <typename T> declares T as a type parameter.

3 Match each piece to its role

Term Meaning
template <typename T> Type parameter declaration
T Type parameter name
identity(42) Call with int
return x Returns the input

All lessons in Intermediate