SoFunction
Updated on 2025-04-13

Introduction to the simple use and difference between function templates and class templates in C++

In C++, templates are the core mechanism for implementing generic programming, allowing developers to write type-independent code. The following is a detailed introduction and practical examples of function templates and class templates.

1. Function template

definition

Function templates implement generic operations through parameterized types. You only need to write code once to process multiple data types, avoiding duplication.

grammar

template<typename T>
Return type Function name(Parameter list) { ... }

typename TRepresents a type placeholder and is automatically instantiated according to the actual parameter type during compilation.

Real examples

‌Swap two values ​​(swap

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

Use scenarios‌: Exchange variables of any type (such asintstring)。

int x = 1, y = 2;
swap(x, y);  // Automatically deduced as swap&lt;int&gt;

Find the maximum value (max

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

Use scenarios‌: Compare the maximum value of the same type value, and require type supportoperator>

Print an array

int nums[] = {1, 2, 3};
printArray(nums);  // Deduction T=int, N=3

2. Class templates

definition

Class templates allow the creation of classes that can handle multiple data types, and template parameters can be used for member variables and functions.

grammar

template&lt;typename T&gt;
class Class Name {
    // Class members use T as type};

Real examples

‌Dynamic Array(Array

template<typename T>
class Array {
private:
    T* data;
    size_t size;
public:
    Array(size_t size) : size(size), data(new T[size]) {}
    ~Array() { delete[] data; }
    T& operator[](size_t index) { return data[index]; }
    size_t getSize() const { return size; }
};

Use scenarios‌: Store dynamic arrays of any type.

Array&lt;int&gt; intArr(10);    // Arrays that store intArray&lt;string&gt; strArr(5);  // storage string Array of

‌Key-value pairs (Pair

template<typename T1, typename T2>
class Pair {
public:
    T1 first;
    T2 second;
    Pair(const T1 &f, const T2 &s) : first(f), second(s) {}
};

Use scenarios‌: Combining two different types of data (such as dictionary entries).

Pair&lt;string, int&gt; student("Alice", 90);  // Name and score

‌Stack(Stack

template<typename T>
class Stack {
private:
    std::vector<T> elements;
public:
    void push(const T &elem) { elements.push_back(elem); }
    T pop() {
        if (()) throw std::out_of_range("Stack is empty!");
        T elem = ();
        elements.pop_back();
        return elem;
    }
};

Use scenarios‌: Implements a generic stack structure and supports multiple data types.

Stack<double> doubleStack;
(3.14);

3. Key differences

characteristic Function templates Class templates
Type Derivation Automatically deduce parameter types (no explicit specification required) The type must be specified explicitly (such asStack<int>
Default template parameters Support (from C++11) Support (such astemplate<typename T = int>
Typical Applications Algorithms (such as sorting, exchange) Containers (such as arrays, stacks, queues)

4. Things to note

  • Compilation method‌: Template code is usually placed in header files because the compiler needs to generate specific types of instantiated code at compile time. ‌
  • Type constraints‌: Operations in templates (such asoperator>) Need in typeTDefinition in  , otherwise the compilation fails. ‌
  • performance‌: The template expands at compile time, without runtime overhead, but may increase the code volume.

By using templates reasonably, code reusability can be greatly improved while maintaining type safety and high performance. For example, thevectorsortAll are implemented based on templates.

This is the article about the simple use of function templates and class templates in C++. For more related contents of C++ function templates and class templates, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!