π Lecture 33 β Templates: Advanced Concepts and Policy-Based Design
π Overview: This lecture explores advanced template concepts in C++, including multiple type arguments for conversion functions, using templates with user-defined types, and the distinction between function overloading and templates. The core focus is on using template arguments as "policy" to change behaviorβdemonstrated through a sophisticated string comparison function that can be configured for case-sensitive or case-insensitive comparisons at compile time.
ποΈ Topics Covered
Multiple type arguments for template functions enabling type conversion between different data types. Using user-defined types (like String classes) as template arguments and the importance of defining required operators (like ==) for template functions to work correctly. The distinction between function overloading (different implementations for different types) and function templates (identical operations across types). Template arguments as policy to change behavior at compile time, illustrated through three solutions for implementing case-sensitive and case-insensitive string comparison.
π Lecture Summary
Recap
Templates are generic abstractions in C++ that come in two kinds: Function Templates and Class Templates. A general template can be specialized to handle a particular type, such as the char [] type.
33.1. Multiple Type Arguments
When writing code to convert different types into one another (like char to int or float to int), the concept of templates can be used with multiple type arguments. This avoids writing many separate functions for each type conversion.
template< typename T, typename U >
T my_cast( U u ) {
return (T)u; // U type will be converted to T type and will be returned
}
int main() {
double d = 10.5674;
int j = my_cast( d ); // Error: cannot deduce T
int i = my_cast< int >( d ); // OK: explicitly specify T as int
return 0;
}
π Definition β Multiple Type Arguments: Template parameters that allow a function template to accept and work with two or more different data types simultaneously.
π Formula: template< typename T, typename U > T functionName( U u ) β Converts type U to type T and returns the result.
π Example: When calling my_cast< int >( d ) where d is a double (10.5674), the function returns (int)10.5674 which equals 10, performing an explicit type conversion from double to int.
π‘ Why this matters: The compiler cannot deduce type T when it's only used as the return type and not in the parameter listβyou must explicitly specify it.
33.2. User-Defined Types
Besides primitive types, user-defined types can also be passed as type arguments to templates. The compiler performs static type checking to diagnose type errors at compile time.
Consider a String class without an overloaded == operator:
class String {
char* pStr;
// Operator "==" not defined
};
template< typename T >
bool isEqual( T x, T y ) {
return ( x == y );
}
int main() {
String s1 = "xyz", s2 = "xyz";
isEqual( s1, s2 ); // Error! No == operator defined for String
return 0;
}
To use the String class with the isEqual template, we must define the overloaded == operator as a friend function:
class String {
char* pStr;
friend bool operator ==( const String&, const String& );
};
bool operator ==( const String& x, const String& y ) {
return strcmp(x.pStr, y.pStr) == 0;
}
template< typename T >
bool isEqual( T x, T y ) {
return ( x == y );
}
int main() {
String s1 = "xyz", s2 = "xyz";
isEqual( s1, s2 ); // OK now
return 0;
}
π Definition β Static Type Checking: Compile-time verification that the types used with a template support all the operations performed inside the template function.
33.3. Overloading vs. Templates
Function templates are used when we want to have exactly identical operations on different data types. With templates, we cannot change the implementation from one data type to another without using specialization.
Function overloading is used when we want to have similar but slightly different operations on different data types, allowing different implementations for each type.
π Example:
- Overloading: The
+operator is overloaded for different types of operands (String+String, char*+String, etc.) with different implementations in each case. - Templates: A single function template can calculate the sum of an array of many numeric types with identical logic.
// Function Overloading (different implementations)
String operator +( const String& x, const String& y ) { ... }
String operator +( const char * str1, const String& y ) { ... }
// Function Template (identical operations)
template< class T >
T sum( T* array, int size ) {
T sum = 0;
for (int i = 0; i < size; i++)
sum = sum + array[i];
return sum;
}
33.4. Template Arguments as Policy
We can change the behavior of a template using a template parameter. We can pass a template argument to enforce some rule or policy. The problem: "Write a function that compares two given character strings" that can perform both case-sensitive and case-insensitive comparisons.
33.5. First Solution: Two Separate Functions
Write two separate functions and call the appropriate one as needed.
Case-sensitive comparison (returns 0 if strings are identical and same length):
int caseSencompare( char* str1, char* str2 ) {
for (int i = 0; i < strlen( str1 ) && i < strlen( str2 ); ++i)
if ( str1[i] != str2[i] )
return str1[i] - str2[i];
return strlen(str1) - strlen(str2);
}
Case-insensitive comparison (returns 0 if strings have same alphabets ignoring case):
int nonCaseSencompare( char* str1, char* str2 ) {
for (int i = 0; i < strlen( str1 ) && i < strlen( str2 ); i++)
if ( toupper( str1[i] ) != toupper( str2[i] ) )
return str1[i] - str2[i];
return strlen(str1) - strlen(str2);
}
33.6. Second Solution: Using a Bool Parameter
Write a single compare function and pass a bool parameter to indicate the type of comparison.
int compare( char* str1, char* str2, bool caseSen ) {
for (int i = 0; i < strlen( str1 ) && i < strlen( str2 ); i++)
if ( (caseSen && str1[i] != str2[i]) ||
(!caseSen && toupper(str1[i]) != toupper(str2[i])) )
return str1[i] - str2[i];
return strlen(str1) - strlen(str2);
}
π Definition β Policy Flag: A boolean parameter used at runtime to determine which behavior to execute within a single function implementation.
When caseSen is true (1), it activates the left sub-expression (caseSen && str1[i] != str2[i]). When caseSen is false, it activates the right sub-expression (!caseSen && toupper(str1[i]) != toupper(str2[i])).
33.7. Third Solution: Template Policy Classes (Most Elegant)
Write two classesβone for case-sensitive and one for case-insensitive comparisonβand pass one of these classes as a template argument. The template function calls the isEqual function of the passed class.
class CaseSenCmp {
public:
static int isEqual( char x, char y ) {
return x == y;
}
};
class NonCaseSenCmp {
public:
static int isEqual( char x, char y ) {
return toupper(x) == toupper(y);
}
};
template< typename C >
int compare( char* str1, char* str2 ) {
for (int i = 0; i < strlen( str1 ) && i < strlen( str2 ); i++)
if ( !C::isEqual (str1[i], str2[i]) )
return str1[i] - str2[i];
return strlen(str1) - strlen(str2);
}
int main() {
int i, j;
char *x = "hello", *y = "HELLO";
i = compare< CaseSenCmp >(x, y);
j = compare< NonCaseSenCmp >(x, y);
cout << "Case Sensitive: " << i; // Output: 32 (Not Equal)
cout << "\nNon-Case Sensitive: " << j; // Output: 0 (Equal)
return 0;
}
π Definition β Policy Class: A class that encapsulates a specific behavior (like comparison logic) and is passed as a template argument to configure the template's behavior at compile time.
33.8. Default Policy
We can set a default class type as the default comparison type, similar to setting default parameters in constructors.
template< typename C = CaseSenCmp >
int compare( char* str1, char* str2 ) {
for (int i = 0; i < strlen( str1 ) && i < strlen( str2 ); i++)
if ( !C::isEqual (str1[i], str2[i]) )
return str1[i] - str2[i];
return strlen(str1) - strlen(str2);
}
int main() {
int i, j;
char *x = "hello", *y = "HELLO";
i = compare(x, y); // Uses default: CaseSenCmp
j = compare< NonCaseSenCmp >(x, y); // Explicit: NonCaseSenCmp
cout << "Case Sensitive: " << i;
cout << "\nNon-Case Sensitive: " << j;
return 0;
}
π Definition β Default Template Argument: A type parameter with a default value (= CaseSenCmp) that allows the template to be used without explicitly specifying the policy class.
β Key Takeaways
You must understand that templates can accept multiple type arguments for type conversion functions, but the compiler cannot deduce return-type-only template parametersβthey must be explicitly specified. When using templates with user-defined types, ensure all required operators (like ==) are properly defined, or the compiler will produce type errors during static checking. The critical distinction is that function templates provide identical operations across types while function overloading allows different implementations. Template arguments can serve as compile-time "policies" to change behavior without runtime overhead, which is the most elegant solution compared to using separate functions or runtime boolean flags. Default template arguments allow you to provide sensible default behavior while still enabling customization.
π§ Quick Revision Questions
- When using multiple type arguments in a template function, why must you explicitly specify the return type parameter in the function call?
- What must be defined for a user-defined class to work correctly as a template argument for a function template that uses
==? - What is the key difference between function overloading and function templates regarding implementation flexibility?
- In the third solution for string comparison, why are the
isEqualfunctions declared asstaticinside the policy classes? - How does setting a default template argument (like
= CaseSenCmp) affect how thecomparefunction is called?
π Lecture 34 β Generic Algorithms - A Case Study
π Overview: This lecture demonstrates how to transform a type-specific function into a fully generic algorithm that works independently of both data types and data structures. It walks through the step-by-step evolution of a
findfunction from array-specific code to a genuinely generic algorithm, and then extends the same principles to create a class template for a Vector container.
ποΈ Topics Covered
The lecture covers the concept of generic algorithms that are independent of both data types and data structures, starting with the transformation of the printArray template function into a more flexible form. It then works through a case study of converting an integer-specific find function into a fully generic template function by removing size parameters, using "beyond" pointers, and finally eliminating pointer dependencies. The lecture concludes with class templates and a complete implementation of a generic Vector class.
π Lecture Summary
34.1. Generic Algorithms
Generic programming aims to create functions that work for all types of containers, not just arrays. The lecture uses a find function as a case study to demonstrate step-by-step evolution toward true genericity. Starting with an integer-specific version that takes an array and its size, the function is progressively transformed into a fully generic algorithm.
The first step is converting the function into a template function so it works for all data types:
template< typename T >
T* find( T* array, int _size, const T& x ) {
T* p = array;
for (int i = 0; i < _size; i++) {
if ( *p == x )
return p;
p++;
}
return 0;
}
The next step replaces the size parameter with a "beyond" pointer β a pointer to one position past the last element. This simplifies the code and makes it more generic:
template< typename T >
T* find( T* array, T* beyond, const T& x ) {
T* p = array;
while ( p != beyond ) {
if ( *p == x )
return p;
p++;
}
return beyond;
}
π‘ Why this matters: Using a "beyond" pointer instead of a size parameter allows the function to work with any contiguous memory range, including sub-arrays or slices of larger arrays.
The function is further simplified by combining the termination check and comparison in the while condition, and using a single return statement:
template< typename T >
T* find( T* array, T* beyond, const T& x ) {
T* p = array;
while ( p != beyond && *p != x )
p++;
return p;
}
The final and most important step removes all pointer notation, making the function truly independent of data structure. The function now works with any container that supports two operations: increment operator (++) and dereference operator (*):
template< typename P, typename T >
P find( P start, P beyond, const T& x ) {
while ( start != beyond && *start != x )
start++;
return start;
}
This generic version can be called with arrays, lists, or any container that supports ++ and *:
int main() {
int iArray[5];
iArray[0] = 15;
iArray[1] = 7;
iArray[2] = 987;
// ...
int* found;
found = find(iArray, iArray + 5, 7);
return 0;
}
π Definition β Generic Algorithm: A function or algorithm that works for any data type and any container (data structure), as long as the container supports the required operations (like ++ and *).
34.2. Class Templates
A class template provides functionality to operate on different types of data, facilitating reuse of classes. Just as function templates allow a single function to work with multiple types, class templates allow a single class definition to work with multiple types.
A class template can be defined in two equivalent ways:
template< class T > class Xyz { ... };template< typename T > class Xyz { ... };
The keyword class and typename are interchangeable in this context. The lecture now builds a template Vector class that can store any type of data, including objects that are themselves collections.
π Definition β Class Template: A blueprint for creating classes that operate on different data types. The actual class is generated when the template is instantiated with a specific type.
34.3. Example β Class Template
The lecture presents a complete Vector class template that can store data elements of different types. Without templates, a separate Vector class would be needed for each data type.
Class Definition:
template< class T >
class Vector {
private:
int size;
T* ptr;
public:
Vector<T>( int = 10 );
Vector<T>( const Vector< T >& );
~Vector<T>();
int getSize() const;
const Vector< T >& operator =( const Vector< T >& );
T& operator []( int );
};
Implementation:
// Constructor
template< class T >
Vector<T>::Vector<T>( int s ) {
size = s;
if ( size != 0 )
ptr = new T[size];
else
ptr = 0;
}
// Copy Constructor
template< class T >
Vector<T>:: Vector<T>( const Vector<T>& copy ) {
size = copy.getSize();
if (size != 0) {
ptr = new T[size];
for (int i = 0; i < size; i++)
ptr[i] = copy.ptr[i];
}
else ptr = 0;
}
// Destructor
template< class T >
Vector<T>::~Vector<T>() {
delete [] ptr;
}
// getSize function
template< class T >
int Vector<T>::getSize() const {
return size;
}
// Assignment Operator
template< class T >
const Vector<T>& Vector<T>::operator =( const Vector<T>& right) {
if ( this != &right ) {
delete [] ptr;
size = right.size;
if ( size != 0 ) {
ptr = new T[size];
for(int i = 0; i < size;i++)
ptr[i] = right.ptr[i];
}
else
ptr = 0;
}
return *this;
}
// Subscript Operator
template< class T >
T& Vector< T >::operator []( int index ) {
if ( index < 0 || index >= size ) {
cout << "Error: index out of range\n";
exit( 1 );
}
return ptr[index];
}
Instantiation examples:
Vector< int > intVector; // Creates a Vector of integers
Vector< char > charVector; // Creates a Vector of characters
The Vector class is a parameterized class β it must always be instantiated for a particular type. You cannot create an object of type Vector alone; it must be Vector<int>, Vector<float>, etc.
π Definition β Parameterized Class: A class template that must be instantiated with a specific data type before objects can be created.
π Example:
Vector< int > intVector; // Valid - creates Vector of ints
Vector< char > charVector; // Valid - creates Vector of chars
// Vector unknownVector; // Invalid - must specify type
β Key Takeaways
The most critical concept is that generic algorithms achieve true independence from both data types and data structures by using template parameters and supporting only essential operations like ++ and *. The step-by-step evolution of the find function β from integer-specific to template, then replacing size with a beyond pointer, and finally removing all pointer notation β demonstrates this principle clearly. The Vector class template shows how the same generic approach applies to classes, allowing a single class to work with any data type while handling dynamic memory management through constructors, destructors, and copy assignment.
π§ Quick Revision Questions
- What are the two essential operations a container must support for a generic algorithm to work with it?
- Why is using a "beyond" pointer better than passing the size of an array to a generic function?
- In the final generic
findfunction, what does the template parameterPrepresent? - What is the difference between a function template and a class template?
- Why must the Vector class always be instantiated with a specific type (e.g.,
Vector<int>) rather than justVector?
π Lecture 35 β Member Templates and Class Template Specialization
π Overview: This lecture covers advanced template concepts in C++ β member templates that allow template classes to handle multiple data types, and class template specialization for handling specific types differently. Understanding these concepts is crucial for writing flexible, type-safe generic code that handles edge cases properly.
ποΈ Topics Covered
Member function templates within template classes for cross-type operations like copy constructors, the need for explicit template parameters beyond the class template parameter, code generation optimization to avoid code bloat, and class template specialization for char arrays to handle deep copying and memory management correctly.
π Lecture Summary
35.1. Member Templates
Member functions of a template class implicitly become function templates that work for instantiations (int, char, float, double, etc.) of that class. However, situations arise where we need explicit template functions taking more template parameters besides the implicit one (the parameter given to the class when creating its object).
A class or class template can have member functions that are themselves templates. When declaring a class in C++, there is no need to mention the template parameter for class member functions as the compiler implicitly understands it. However, if using another template parameter (like in a copy constructor), we must give its name explicitly.
π Definition β Member Template: A template member function within a class template that takes additional template parameters beyond the class's own template parameter.
The problem arises when assigning Complex class instances of different types:
template<typename T> class Complex {
T real, imag;
public:
Complex(T r, T im) : real(r), imag(im) {}
Complex(const Complex<T>& c) : real(c.real), imag(c.imag) {}
};
int main() {
Complex<float> fc(0, 0);
Complex<double> dc = fc; // Error!
return 0;
}
This fails because the copy constructor only accepts same-type arguments. When creating a Complex<double> object, the compiler generates:
class Complex<double> {
double real, imag;
public:
Complex(double r, double im) : real(r), imag(im) {}
Complex(const Complex<double>& c) : real(c.real), imag(c.imag) {}
};
The solution is to make the copy constructor an explicit member template:
template<typename T> class Complex {
T real, imag;
public:
Complex(T r, T im) : real(r), imag(im) {}
template <typename U>
Complex(const Complex<U>& c) : real(c.real), imag(c.imag) {}
};
Now the assignment works:
int main() {
Complex<float> fc(0, 0);
Complex<double> dc = fc; // OK
return 0;
}
Here, the copy constructor is instantiated with implicit template type T = double and explicit template type U = float.
Important notes:
- Only the required instantiation of the copy constructor is generated
- Good compilers only generate required template function instances to avoid code bloat (unnecessary code generation)
For Complex<double> dc = fc;, only the <double> instantiation gets the member template copy constructor, while the <float> instantiation doesn't generate one since it's not needed.
π‘ Why this matters: Member templates allow type conversion between template instantiations without writing separate conversion functions for each type pair, while keeping code generation minimal.
35.2. Class Template Specialization
Like function templates, a class template may not handle all types successfully. For *char arrays (char)**, the behavior of a template class Vector may not be as desired.
For a Vector<int> (integers), shallow copy works fine. But for Vector<char*>:
int main() {
Vector<char*> sv1(2);
sv1[0] = "Aamir"; // stores pointer to const string
sv1[1] = "Nasir";
Vector<char*> sv2(sv1); // shallow copy issue
Vector<char*> sv3(2);
sv3 = sv1; // shallow copy issue
return 0;
}
We write an explicit specialization for Vector<char*>:
template<>
class Vector<char*> {
private:
int size;
char** ptr;
public:
Vector(int = 10);
Vector(const Vector<char*>&);
virtual ~Vector();
int getSize() const;
const Vector<char*>& operator=(const Vector<char*>&);
const char*& operator[](int);
void insert(char*, int);
};
Key implementation differences from the general template:
Constructor: Allocates array of char pointers, initializes each to null
template<>
Vector<char*>::Vector(int s) {
size = s;
if (size != 0) {
ptr = new char*[size];
for (int i = 0; i < size; i++) ptr[i] = 0;
} else ptr = 0;
}
Copy constructor: Performs deep copy β allocates new memory and uses strcpy
template<>
Vector<char*>::Vector(const Vector<char*>& copy) {
size = copy.getSize();
if (size == 0) { ptr = 0; return; }
ptr = new char*[size];
for (int i = 0; i < size; i++)
if (copy.ptr[i] != 0) {
ptr[i] = new char[strlen(copy.ptr[i]) + 1];
strcpy(ptr[i], copy.ptr[i]);
} else ptr[i] = 0;
}
Destructor: Deletes each string and the array
template<>
Vector<char*>::~Vector() {
for (int i = 0; i < size; i++) delete[] ptr[i];
delete[] ptr;
}
Assignment operator: Self-assignment check, clean up old memory, deep copy all strings
template<>
const Vector<char*>& Vector<char*>::operator=(const Vector<char*>& right) {
if (this == &right) return *this;
for (int i = 0; i < size; i++) delete[] ptr[i];
delete[] ptr;
size = right.size;
if (size == 0) { ptr = 0; return *this; }
ptr = new char*[size];
for (int i = 0; i < size; i++)
if (right.ptr[i] != 0) {
ptr[i] = new char[strlen(right.ptr[i]) + 1];
strcpy(ptr[i], right.ptr[i]);
} else ptr[i] = 0;
}
Subscript operator: Returns reference to char pointer
template<>
const char*& Vector<char*>::operator[](int index) {
if (index < 0 || index >= size) {
cout << "Error: index out of range\n";
exit(1);
}
return ptr[index];
}
Insert function: Properly handles dynamic memory
template<>
void Vector<char*>::insert(char* str, int i) {
delete[] ptr[i];
if (str != 0) {
ptr[i] = new char[strlen(str) + 1];
strcpy(ptr[i], str);
} else ptr[i] = 0;
}
Usage in main:
int main() {
Vector<char*> sv1(2);
sv1.insert("Aamir", 0); // must use insert, not assignment
sv1.insert("Nasir", 1);
Vector<char*> sv2(sv1); // deep copy works
Vector<char*> sv3(2);
sv3 = sv1; // deep copy works
return 0;
}
Note: The subscript operator returns a const reference, so direct assignment like sv1[0] = "Aamir" fails. The insert function must be used instead.
π‘ Why this matters: Class template specialization allows custom behavior for specific types that need special handling (like dynamic memory management for char arrays), while keeping the same interface as the general template.
β Key Takeaways
Class template specialization is essential when the generic template behavior is incorrect for specific types, particularly when dealing with pointers and dynamic memory. Member templates enable cross-type operations within template classes by adding explicit template parameters. Good compilers optimize code generation to avoid bloat by only instantiating what's needed. For char arrays in class templates, always provide explicit specialization with deep copy semantics to prevent dangling pointers and memory leaks. The insert function approach for char arrays ensures proper memory management compared to direct assignment via subscript operators.
π§ Quick Revision Questions
- Why does
Complex<double> dc = Complex<float> fcfail with a regular copy constructor, and how does a member template fix it? - What is code bloat and how do good compilers avoid it when instantiating member templates?
- What issues arise when using a generic Vector class template with char* data?
- In the char* specialization, why does the subscript operator return a const reference, and what must be used instead?
- How does the copy constructor in the char* specialization differ from the general template version?
π Lecture 36 β Member Templates & Specializations
π Overview: This lecture explores advanced template concepts in C++, including member templates for ordinary classes, partial and complete specialization of class and function templates, and non-type parameters. Understanding these concepts is crucial for creating flexible, type-safe generic code that can handle different data types efficiently.
ποΈ Topics Covered
The lecture covers member templates for ordinary classes, partial specialization vs complete specialization of class templates, function template specializations, using different specializations in practice, non-type parameters in templates, template class Array with non-type parameters, default non-type parameters, and default type parameters.
π Lecture Summary
Recap
We saw in previous lecture how we can implement our programming problems easily using Generic Algorithms. Then we saw how we can add explicit template functions to our Class templates to add our desired functionality. A class template may not handle all the types successfully; explicit specializations are required to deal with such types. We can implement the concept of template specialization for such classes as well as we did for function templates.
36.1. Member Templates Revisited
We can add member templates for ordinary classes as well. For example, the following code adds any instance of Complex class to ComplexSet class. The Complex class can be instantiated for int, float, or double, and ComplexSet class will be a collection of Complex class instantiations.
class ComplexSet {
template<class T>
insert(Complex<T> c) // any instance of complex class
{
// Add instance Complex class to Complex set class
}
};
int main() {
Complex<int> ic(10, 5);
Complex<float> fc(10.5, 5.7);
Complex<double> dc(9.567898, 5);
ComplexSet cs;
cs.insert(ic);
cs.insert(fc);
cs.insert(dc);
return 0;
}
This shows that even an ordinary (non-template) class can have template member functions, allowing it to accept arguments of various template instantiations.
π‘ Why this matters: Member templates in ordinary classes enable generic member functions without making the entire class a template.
36.2. Partial Specialization
We can perform partial specialization instead of complete specialization. A partial specialization of a template exists between general specialization and complete specialization. For example, we can specialize a class to behave in a certain manner in case of pointers or in case of a parameter of a certain type.
The difference between complete and partial specialization:
template<class T, class U, class V> // general template
template<class T, class U, int> // partial specialization
template<class T, float, int> // partial specialization
template<int, float, int> // complete specialization
In partial specialization, the number of template parameters remains the same; however, their nature varies (they become more specific).
Example β Partial Specialization:
template<class T>
class Vector { };
template<class T>
class Vector<T*> { }; // Here T can take any type pointer
template<class T, class U, class V>
class A {};
template<class T, class V>
class A<T, T*, V> {}; // parameters in header are two but in class using same three parameters
template<class T, class U, int I>
class A<T, U, I> {}; // changed third parameter to non-type parameter
template<class T>
class A<int, T*, 5> {}; // first parameter non-type, second T*, third constant 5
Example β Complete Specialization:
template<class T>
class Vector { };
template<>
class Vector<char*> { };
template<class T, class U, class V>
class A {};
template<>
class A<int, char*, double> {};
π Definition β Non-type parameters: Non-type parameters are those parameters which are not template parameters (not types like class T, but values like int I).
36.3. Function Templates
Similar to class templates, a function template may also have partial specializations.
Example β Partial Specialization for functions:
template<class T, class U, class V>
void func(T, U, V);
template<class T, class V>
void func(T, T*, V);
template<class T, class U, int I>
void func(T, U);
template<class T>
void func(int, T, 7);
36.4. Complete Specialization
We have already used complete specialization in case of function templates.
Example β Complete specialization with isEqual:
template<typename T>
bool isEqual(T x, T y) {
return (x == y);
}
template<typename T>
bool isEqual(T* x, T* y) {
return (*x == *y);
}
template<>
bool isEqual<const char*>(const char* x, const char* y) {
return (strcmp(x, y) == 0);
}
The complete specialization isEqual<const char*> provides custom behavior for C-style strings, using strcmp instead of operator==.
36.5. Using Different Specializations
The code below shows how we can use different types of specializations for the isEqual function:
int main() {
int i, j;
char* a, b;
Shape *s1 = new Line();
Shape *s2 = new Circle();
isEqual(i, j); // Template (general)
isEqual(a, b); // Complete Specialization (const char*)
isEqual(s1, s2); // Partial Specialization (T*)
return 0;
}
36.6. Non-type Parameters
The parameters given in template definition other than those used for mentioning template types are called non-type parameters. For example:
template <class T, class U, int I>
Here int I is a non-type parameter. Template parameters may include non-type parameters, and non-type parameters may have default values:
template <class T, class U, int I = 5>
They are treated as constants and are commonly used for static memory allocation β meaning when we want to pass the length of memory we need in the template at compile time (statically).
36.7. Example β template class Array
Consider the Array class again that we discussed in template classes introduction. In this template array class, we create a C++ array of any built-in data type by passing array size in Array object constructor:
template<class T>
class Array {
private:
T* ptr;
public:
Array(int size);
~Array();
// ...
};
template<class T>
Array<T>::Array() {
if (size > 0)
ptr = new T[size];
else
ptr = NULL;
}
int main() {
Array<char> cArray(10);
Array<int> iArray(15);
Array<double> dArray(20);
return 0;
}
We can do the same by passing the array size as a non-type parameter while creating an Array class object itself:
template<class T, int SIZE>
class Array {
private:
T ptr[SIZE];
public:
Array();
// ...
};
int main() {
Array<char, 10> cArray;
Array<int, 15> iArray;
Array<double, 20> dArray;
return 0;
}
Now the array size is part of the type and known at compile time, allowing stack allocation (T ptr[SIZE] instead of dynamic allocation with new).
π Formula: Array<T, SIZE> β A class template where SIZE is a compile-time constant determining array length
36.8. Default Non-type Parameters
We can set default values for non-type parameters, as we do for parameters passed in ordinary functions:
template<class T, int SIZE = 10>
class Array {
private:
T ptr[SIZE];
public:
void doSomething();
// ...
};
int main() {
Array<char> cArray; // here Array of size 10 will be created
return 0;
}
When no size is specified, the default value 10 is used.
36.9. Default Type Parameters
We can also specify default type for type parameters (template parameters like T, U, V). Consider the Vector class again:
template<class T = int> // default type for Vector class is now int
class Vector {
// ...
};
Vector<> v; // same as Vector<int> v
When no type is specified, the default type (int) is used.
β Key Takeaways
Member templates allow ordinary (non-template) classes to have template member functions, enabling them to accept various template instantiations. Partial specialization provides a middle ground between general and complete templates, allowing specific behaviors for certain parameter patterns (like pointers) while keeping other parameters generic. Non-type parameters enable compile-time constants to be passed as template arguments, which is essential for static memory allocation and compile-time optimizations. Default values for both type and non-type parameters make templates more convenient to use by providing sensible defaults. Understanding the hierarchy of general template, partial specialization, and complete specialization is critical for designing flexible yet type-safe generic code in C++.
π§ Quick Revision Questions
- What is the difference between partial specialization and complete specialization of a class template?
- How would you create an Array class that uses a non-type parameter for size, and what advantage does this provide over passing size to the constructor?
- What happens when you write
Vector<> v;if the Vector template has a default type parameter ofint? - Write a template function
isEqualwith a general version, a partial specialization for pointers, and a complete specialization forconst char*. - Can an ordinary (non-template) class have template member functions? Provide an example involving a
ComplexSetclass and aComplex<T>class.
π Lecture 37 β Resolution Order
π Overview: This lecture explains how the compiler resolves which template specialization to use when multiple specializations exist, covering both class templates and function templates. It also details how inheritance works with templates, including rules and valid/invalid derivation patterns across general, partial, and complete specializations.
ποΈ Topics Covered
The lecture covers resolution order for class template specializations, function template overloading and its resolution order, templates and inheritance rules, derivations for general template classes, partially specialized classes, completely specialized classes, and ordinary classes β with numerous code examples showing valid and invalid inheritance patterns.
π Lecture Summary
37.1. Resolution Order
When a compiler encounters a template class with multiple specializations (from partial to complete), it searches through these specializations in a specific sequence called resolution order. This is the order from most specific to most general.
π Definition β Resolution Order: The sequence in which the compiler searches for the required template specialization: first complete specialization, then partial specialization, then general template.
Resolution Order: a. First, compiler looks for complete specialization b. If not found, it searches for partial specialization c. Finally, it searches for the general template
Example β Resolution Order
template< typename T >
class Vector { ... }; // general template
template< typename T >
class Vector< T* > { ... }; // partial specialization for pointers
template< >
class Vector< char* > { ... }; // complete specialization for char*
int main() {
Vector< char* > strVector; // complete specialization used
Vector< int* > iPtrVector; // partial specialization used
Vector< int > intVector; // general template used
return 0;
}
Explanation:
- For
Vector< char* >: Compiler finds the complete specializationVector< char* >first and stops. - For
Vector< int* >: No complete specialization exists forint*(only forchar*), so compiler moves to partial specialization and findsVector< T* >which works for all pointer types. - For
Vector< int >: No complete or partial specialization matchesint, so compiler uses the general templateVector< T >.
π‘ Why this matters: Understanding resolution order ensures you know exactly which version of a template will execute, preventing unexpected behavior.
37.2. Function Template Overloading
We can also specialize function templates, which is called function template overloading.
template< typename T >
void sort( T ); // general template function
template< typename T >
void sort( Vector< T > & ); // specialization for Vector of any type
template< >
void sort< Vector<char*> >( Vector< char* > & ); // specialization for Vector<char*>
void sort( char* ); // ordinary function for char*
37.3. Resolution Order
For function templates, the compiler searches in this order:
- Ordinary Function (non-template function with same name)
- Complete Specialization
- Partial Specialization
- Generic Template
Example β Resolution Order
int main() {
char* str = βHello World!β;
sort(str); // Ordinary function sort( char* )
Vector<char*> v1 = {βabβ, βcdβ, ... };
sort(v1); // Complete specialization sort( Vector<char*> & )
Vector<int> v2 = { 5, 10, 15, 20 };
sort(v2); // Partial specialization sort( Vector<T> &)
int iArray[] = { 5, 2, 6, 70 };
sort(iArray); // General template sort( T )
return 0;
}
This follows the same order as class templates but with ordinary functions added at the highest priority.
π‘ Why this matters: Ordinary functions always take precedence over template versions, which prevents unexpected template instantiation when a specific non-template function exists.
37.4. Templates and Inheritance
We can use inheritance with templates or their specializations, but must follow one key rule:
- If we have a template class, all classes derived from it should also be class templates.
- The derived class must take at least as many template parameters as the base class requires for instantiation.
37.5. Derivations in case of a General Template class
A class template may inherit from another class template:
template< class T >
class A { ... };
template< class T >
class B : public A< T > // same template parameter T ensures same instantiation type
{ ... };
int main() {
A< int > obj1;
B< int > obj2;
return 0;
}
A partial specialization may inherit from a class template:
template< class T >
class B< T* > : public A< T > // same template parameter T
{ ... };
int main() {
A< int > obj1;
B< int* > obj2;
return 0;
}
Complete specialization or ordinary class CANNOT inherit from a class template:
template< >
class B< char* > : public A< T > { ... };
// Error: 'T' undefined β derived class takes fewer parameters than base
class B : public A< T > { ... };
// Error: 'T' undefined β ordinary class cannot inherit from template
Derivations in case of a partially specialized class
A class template may inherit from a partial specialization:
class A { ... };
template< class T >
class A< T* > { ... };
template< class T >
class B : public A< T* >
{ ... };
int main() {
A< int* > obj1;
B< int > obj2;
return 0;
}
A partial specialization may inherit from a partial specialization:
template< class T >
class B< T* > : public A< T* >
{ ... };
int main() {
A< int* > obj1;
B< int* > obj2;
return 0;
}
Complete specialization or ordinary class CANNOT inherit from a partial specialization:
template< >
class B< int* > : public A< T* > { ... };
// Error: Undefined 'T'
class B : public A< T* > { ... };
// Error: Undefined 'T'
Derivations in case of Completely Specialized class
A class template may inherit from a complete specialization:
template< class T >
class B : public A< float* >
{ ... };
int main() {
A< float* > obj1;
B< int > obj2;
return 0;
}
A partial specialization may inherit from a complete specialization:
template< class T >
class B< T* > : public A< float* >
{ ... };
int main() {
A< float* > obj1;
B< int* > obj2;
return 0;
}
A complete specialization may inherit from a complete specialization:
template< >
class B< double* > : public A< float* >
{ ... };
int main() {
A< float* > obj1;
B< double* > obj2;
return 0;
}
An ordinary class may inherit from a complete specialization:
class B : public A< float* >
{ ... };
int main() {
A< float* > obj1;
B obj2;
return 0;
}
Derivations in case of Ordinary Class
A class template may inherit from an ordinary class:
class A { ... };
template< class T >
class B : public A
{ ... };
int main() {
A obj1;
B< int > obj2;
return 0;
}
A partial specialization may inherit from an ordinary class:
class A{ };
template<class T>
class B {};
template <class T>
class B<T*>: public A{ };
int main() {
A obj1;
B <int *> obj2;
return 0;
}
A complete specialization may inherit from an ordinary class:
template <class T>
class B{};
template< >
class B< char* > : public A
{ ... };
int main() {
A obj1;
B< char* > obj2;
return 0;
}
β Key Takeaways
The resolution order for class templates is complete specialization β partial specialization β general template, while for function templates it adds ordinary functions first. Inheritance with templates requires the derived class to be a template taking at least as many parameters as the base. Complete specializations and ordinary classes cannot inherit from general or partial template classes because template parameters become undefined. However, any template type (general, partial, or complete) can inherit from a complete specialization or an ordinary class, as these provide concrete types.
π§ Quick Revision Questions
- What is the exact resolution order the compiler follows when searching for class template specializations?
- Why does
class B : public A< T >cause a compilation error? - In function template overloading, what takes priority: an ordinary function or a complete specialization?
- Can a complete specialization inherit from a partial specialization? Why or why not?
- Which of the following is valid: a general template inheriting from an ordinary class, or an ordinary class inheriting from a general template?