Lesson 12-C++ Templates

Function Templates

Function templates are a very powerful feature in C++, allowing you to define a group of related functions that have the same structure but can handle different data types.

Function Template Basics

A function template allows you to write a generic function that can be used with multiple data types. The basic syntax of a function template is as follows:

template <typename T>
return_type function_name(parameters) {
    // function body
}

The keyword typename can be replaced with class; both are equivalent in the context of templates.

Below is a function template that returns the larger of two objects:

template<typename T>
T max(T a,T b){
    return a > b ? a : b;
}

This should be straightforward, even though we haven’t yet started discussing the syntax of function templates.

If you want to declare a function template, you typically use:

template< parameter list > function declaration

In our earlier example, the parameter list is typename T. As the name suggests, the keyword typename introduces a type parameter.

The type parameter is T, but you can use other identifiers as type parameter names (T or Ty are conventional), and you can also define meaningful names when needed. When calling the function template max, the compiler can deduce the type of the type parameter based on the passed arguments and instantiate the function template. We need to pass types that support the operations in the function template, such as int or a class that overloads the > operator. Note that the return in max means our template parameter T must also be copyable/movable to be returned.

Using Templates

Below is an example of how to use the function template max():

#include <iostream>

template<typename T>
T max(T a, T b) {
    return a > b ? a : b;
}

struct Test{
    int v_{};
    Test() = default;
    Test(int v) :v_(v) {}
    bool operator>(const Test& t) const{
        return this->v_ > t.v_;
    }
};

int main(){
    int a{ 1 };
    int b{ 2 };
    std::cout << "max(a, b) : " << ::max(a, b) << '\n';

    Test t1{ 10 };
    Test t2{ 20 };
    std::cout << "max(t1, t2) : " << ::max(t1, t2).v_ << '\n';

}

It indeed looks no different from calling a regular function. So, what does the compiler do compared to calling a regular function?

The compiler will instantiate two functions, meaning it generates a max function with int parameters and another with Test parameters.

int max(int a, int b)
{
  return a > b ? a : b;
}

Test max(Test a, Test b)
{
  return a > b ? a : b;
}

Example 1: Maximum Value Function

Below is a simple function template example used to find the maximum of two numbers.

#include <iostream>

template <typename T>
T max(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    int x = 10, y = 20;
    double d1 = 3.14, d2 = 2.71;

    std::cout << "Max of " << x << " and " << y << " is " << max(x, y) << std::endl;
    std::cout << "Max of " << d1 << " and " << d2 << " is " << max(d1, d2) << std::endl;

    return 0;
}

Template Parameters

A function template can have multiple template parameters, each of which can have different constraints.

Example 2: Generic Swap Function Below is a generic swap function template that can be used with variables of any type.

#include <iostream>

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

int main() {
    int x = 10, y = 20;
    double d1 = 3.14, d2 = 2.71;

    std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;
    swap(x, y);
    std::cout << "After swap: x = " << x << ", y = " << y << std::endl;

    std::cout << "Before swap: d1 = " << d1 << ", d2 = " << d2 << std::endl;
    swap(d1, d2);
    std::cout << "After swap: d1 = " << d1 << ", d2 = " << d2 << std::endl;

    return 0;
}

Template Argument Deduction

When using a function template (like max()), the template parameters can be deduced from the passed arguments. If two int arguments are passed to T, the compiler will treat T as int.

However, T may only be part of the type. If max() is declared using const&:

template<typename T>
T max(const T& a, const T& b) {
    return a > b ? a : b;
}

If we call max(1, 2) or max<int>(x,x), T will naturally be int, but the function parameter type will be const int&.

However, we need to be aware that there are many cases where deduction is not possible:

// Omit max
using namespace std::string_literals;

int main(){
    max(1, 1.2);            // Error: Cannot determine whether T should be int or double
    max("luse"s, "yue");     // Error: Cannot determine whether T should be std::string or const char[N]
}

So how do we handle such errors? We can use the previously mentioned explicitly specify the type (T) of the function template.

max<double>(1, 1.2);           
max<std::string>("luse"s, "yue");<br>

Alternatively, use explicit type casting:

max(static_cast<double>(1), 1.2);

But std::string cannot be handled this way; we can explicitly construct an unnamed temporary object:

max("luse"s, std::string("yue"));    // Error: Why?<br>

At this point, it’s not that our T is ambiguous, but that the function template max is ambiguous—it conflicts with the standard library’s std::max. Although we didn’t use std::, according to C++ lookup rules,

So how do we resolve this? It’s simple: perform qualified name lookup, using :: or std:: to specify whether you want to call max in the global scope or in the std namespace.

::max("luse"s, std::string("yue"));<br>

Template Specialization

Template specialization allows you to provide different implementations for specific types. This is very useful for handling special types (like pointers, references, etc.).

Example 3: Template Specialization Example Below is a template specialization example used to handle character array comparisons.

#include <iostream>
#include <cstring> // For strlen

template <typename T>
bool isEqual(T a, T b) {
    return a == b;
}

// Specialized version for handling character arrays
template <>
bool isEqual(const char* a, const char* b) {
    return std::strcmp(a, b) == 0;
}

int main() {
    int x = 10, y = 20;
    const char* str1 = "Hello";
    const char* str2 = "World";
    const char* str3 = "Hello";

    std::cout << "x == y: " << isEqual(x, y) << std::endl;
    std::cout << "str1 == str2: " << isEqual(str1, str2) << std::endl;
    std::cout << "str1 == str3: " << isEqual(str1, str3) << std::endl;

    return 0;
}

Default Template Parameters

You can provide default values for template parameters, so that these parameters can be omitted when calling the function template.

Example 4: Using Default Template Parameters Below is an example using default template parameters to compute the product of two numbers.

#include <iostream>

template <typename T, typename U = T>
auto multiply(T a, U b = 1) -> decltype(a * b) {
    return a * b;
}

int main() {
    int x = 10;
    double d1 = 3.14;

    std::cout << "10 * 2 = " << multiply(x, 2) << std::endl;
    std::cout << "3.14 * 2 = " << multiply(d1, 2.0) << std::endl;
    std::cout << "10 * 1 = " << multiply(x) << std::endl;
    std::cout << "3.14 * 1 = " << multiply(d1) << std::endl;

    return 0;
}

Class Templates

Class templates are an important generic programming tool in C++, allowing you to define a group of related classes that have the same structure but can handle different data types.

Class Template Basics

A class template allows you to define a generic class that can be used with multiple data types. The basic syntax of a class template is as follows:

template <typename T>
class ClassName {
public:
    // Member function declarations
private:
    // Member variable declarations
};

The keyword typename can be replaced with class; both are equivalent in the context of templates.

Example 1: Simple Container Class Template Below is a simple container class template example used to store data of different types.

#include <iostream>

template <typename T>
class SimpleContainer {
public:
    void add(T item) {
        data.push_back(item);
    }

    void print() const {
        for (const auto& item : data) {
            std::cout << item << " ";
        }
        std::cout << std::endl;
    }

private:
    std::vector<T> data;
};

int main() {
    SimpleContainer<int> intContainer;
    SimpleContainer<double> doubleContainer;

    intContainer.add(10);
    intContainer.add(20);
    intContainer.print();

    doubleContainer.add(3.14);
    doubleContainer.add(2.71);
    doubleContainer.print();

    return 0;
}

Class Template Member Functions

Member functions of a class template can be defined inside or outside the class template. When defined outside the class template, the template parameters must be explicitly specified.

Example 2: Member Functions Defined Outside the Class Template Below is an example of member functions defined outside the class template.

#include <iostream>
#include <vector>

template <typename T>
class SimpleContainer {
public:
    void add(T item); // Declaration
    void print() const; // Declaration

private:
    std::vector<T> data;
};

// Member function definitions
template <typename T>
void SimpleContainer<T>::add(T item) {
    data.push_back(item);
}

template <typename T>
void SimpleContainer<T>::print() const {
    for (const auto& item : data) {
        std::cout << item << " ";
    }
    std::cout << std::endl;
}

int main() {
    SimpleContainer<int> intContainer;
    SimpleContainer<double> doubleContainer;

    intContainer.add(10);
    intContainer.add(20);
    intContainer.print();

    doubleContainer.add(3.14);
    doubleContainer.add(2.71);
    doubleContainer.print();

    return 0;
}

Class Template Specialization

Class template specialization allows you to provide different implementations for specific types. This is very useful for handling special types (like pointers, references, etc.).

Example 3: Class Template Specialization Example Below is a class template specialization example used to handle character array comparisons.

#include <iostream>
#include <cstring> // For strlen

template <typename T>
class StringComparer {
public:
    bool isEqual(T a, T b) {
        return a == b;
    }
};

// Specialized version for handling character arrays
template <>
class StringComparer<const char*> {
public:
    bool isEqual(const char* a, const char* b) {
        return std::strcmp(a, b) == 0;
    }
};

int main() {
    StringComparer<int> comparerInt;
    StringComparer<const char*> comparerStr;

    int x = 10, y = 20;
    const char* str1 = "Hello";
    const char* str2 = "World";
    const char* str3 = "Hello";

    std::cout << "x == y: " << comparerInt.isEqual(x, y) << std::endl;
    std::cout << "str1 == str2: " << comparerStr.isEqual(str1, str2) << std::endl;
    std::cout << "str1 == str3: " << comparerStr.isEqual(str1, str3) << std::endl;

    return 0;
}

Partial Class Template Specialization

Partial specialization allows you to provide different implementations for a subset of template parameters.

Example 4: Partial Class Template Specialization Example Below is a partial specialization example used to handle arrays of different types.

#include <iostream>
#include <vector>
#include <string>

template <typename T>
class ArrayPrinter {
public:
    void print(const T& arr) {
        for (const auto& item : arr) {
            std::cout << item << " ";
        }
        std::cout << std::endl;
    }
};

// Partial class template specialization for handling string arrays
template <>
class ArrayPrinter<std::vector<std::string>> {
public:
    void print(const std::vector<std::string>& arr) {
        for (const auto& item : arr) {
            std::cout << "\"" << item << "\" ";
        }
        std::cout << std::endl;
    }
};

int main() {
    ArrayPrinter<std::vector<int>> printerInt;
    ArrayPrinter<std::vector<std::string>> printerString;

    std::vector<int> intArray = {1, 2, 3, 4, 5};
    std::vector<std::string> stringArray = {"one", "two", "three"};

    printerInt.print(intArray);
    printerString.print(stringArray);

    return 0;
}

Template Metaprogramming

Template metaprogramming is a technique that uses C++’s template system to perform compile-time computations. This technique allows you to complete complex logical operations at compile time, thereby improving program runtime efficiency and maintainability.

Basic Concepts

Template metaprogramming primarily relies on C++’s template system. Through templates and template specialization, specific code can be generated at compile time to achieve compile-time computation.

Example 1: Compile-Time Factorial Computation Below is a simple template metaprogramming example used to compute factorial at compile time.

#include <iostream>

// Recursive template
template <int N>
struct Factorial {
    static constexpr int value = N * Factorial<N - 1>::value;
};

// Termination condition
template <>
struct Factorial<0> {
    static constexpr int value = 1;
};

int main() {
    // Compute factorial at compile time
    std::cout << "Factorial<5>: " << Factorial<5>::value << std::endl;
    std::cout << "Factorial<10>: " << Factorial<10>::value << std::endl;

    return 0;
}

Recursive Template Specialization

Recursive template specialization is a common pattern in template metaprogramming used to implement recursive algorithms. Recursion is terminated through template specialization.

Example 2: Compile-Time Fibonacci Sequence Computation Below is an example using recursive template specialization to compute the Fibonacci sequence.

#include <iostream>

// Recursive template
template <int N>
struct Fibonacci {
    static constexpr int value = Fibonacci<N - 1>::value + Fibonacci<N - 2>::value;
};

// Termination conditions
template <>
struct Fibonacci<0> {
    static constexpr int value = 0;
};

template <>
struct Fibonacci<1> {
    static constexpr int value = 1;
};

int main() {
    // Compute Fibonacci sequence at compile time
    std::cout << "Fibonacci<10>: " << Fibonacci<10>::value << std::endl;
    std::cout << "Fibonacci<20>: " << Fibonacci<20>::value << std::endl;

    return 0;
}

SFINAE (Substitution Failure Is Not An Error)

SFINAE is an important rule in C++ that allows you to conditionally select certain template instances at compile time. If template instantiation fails, that instance will not be considered.

Example 3: Using SFINAE for Conditional Compilation Below is an example using SFINAE to implement conditional compilation.

#include <iostream>
#include <type_traits>

template <typename T>
typename std::enable_if<!std::is_same<T, void>::value, T>::type get() {
    return T();
}

template <typename T>
typename std::enable_if<std::is_same<T, void>::value, void>::type get() {
    static_assert(false, "Type is void");
}

int main() {
    auto i = get<int>(); // Works normally
    auto v = get<void>(); // Will not be instantiated

    std::cout << "get<int>() = " << i << std::endl;

    return 0;
}

Variadic Template Parameters

Variadic template parameters allow you to create templates that accept an arbitrary number of template parameters.

Example 4: Using Variadic Template Parameters Below is an example using variadic template parameters to compute the sum of multiple integers.

#include <iostream>

template <typename... Args>
struct Sum {
    static constexpr int value = Args::value + Sum<Args...>::value;
};

template <typename First, typename... Args>
struct Sum<First, Args...> {
    static constexpr int value = First::value + Sum<Args...>::value;
};

template <typename First>
struct Sum<First> {
    static constexpr int value = First::value;
};

int main() {
    // Compute sum of multiple integers at compile time
    std::cout << "Sum: " << Sum<int{1}, int{2}, int{3}, int{4}>::value << std::endl;

    return 0;
}
Share your love