← Back to C++ Course | Chapter 11: Templates | Lesson 3 of 5

C++ Class Templates

Defining Class Templates

A class template defines a generic class blueprint, letting you build a single data structure — a stack, a container, a wrapper — that can manage elements of any data type instead of being locked to one specific type.

Example: Defining Class Templates

cpp
#include <iostream>

template <typename T>
class Box {
public:
	T value;
	Box(T v) : value(v) {}
};

int main() {
	Box<int> b(5);
	std::cout << b.value << std::endl;
	return 0;
}

Instantiating Class Templates

To instantiate a class template, you must explicitly specify the data type inside angle brackets when creating an object, since unlike function templates, the compiler generally can't infer a class template's type parameters from constructor arguments alone.

Example: Instantiating Class Templates

cpp
#include <iostream>

template <typename T>
class Box {
public:
	T value;
	Box(T v) : value(v) {}
};

int main() {
	Box<double> b(3.14);
	std::cout << b.value << std::endl;
	return 0;
}

Defining Member Functions Outside the Body

When defining a class template's member function outside the class body, you have to repeat the full template parameter list as a prefix before the function definition, since the compiler needs that context every time it encounters the definition.

Example: Defining Member Functions Outside the Body

cpp
#include <iostream>

template <typename T>
class Box {
public:
	T value;
	Box(T v) : value(v) {}
	T getValue();
};

template <typename T>
T Box<T>::getValue() {
	return value;
}

int main() {
	Box<int> b(10);
	std::cout << b.getValue() << std::endl;
	return 0;
}

Default Template Arguments

You can give a class template's type parameters default types, which lets callers omit the angle-bracket type argument entirely and fall back to a sensible default when they don't need anything more specific.

Example: Default Template Arguments

cpp
#include <iostream>

template <typename T = int>
class Box {
public:
	T value;
	Box(T v) : value(v) {}
};

int main() {
	Box<> b(5);
	std::cout << b.value << std::endl;
	return 0;
}

Non-Type Parameters in Classes

Class templates also accept non-type parameters, such as integers, which is how fixed-size structures like a compile-time-sized array class can bake their capacity directly into the type itself rather than storing it as ordinary runtime data.

Example: Non-Type Parameters in Classes

cpp
#include <iostream>

template <typename T, int Size>
class FixedArray {
public:
	T data[Size];
};

int main() {
	FixedArray<int, 3> arr;
	arr.data[0] = 10;
	std::cout << arr.data[0] << std::endl;
	return 0;
}
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.