C++ Class Templates
In this page:
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: