C templates include class templates and function templates. Class templates allow the creation of classes that can be used with different data types, while function templates can be used with functions of different data types. The main difference between the two is that class templates are instantiated explicitly, and function templates are instantiated implicitly; in class templates, type parameters are visible in the entire class definition, while in function templates they are only visible in the signature.
Class templates and function templates in C
C templates are a powerful language feature that allows us to create Reuse code that can be used with various data types. C provides two types of templates: class templates and function templates.
Class templates
Class templates allow us to create classes that can be used for different data types. In other words, it allows us to create a blueprint that can be used to create objects with different data types such as integers, floats, or other custom classes.
template <typename T> class Array { public: Array(int size) : size(size), data(new T[size]) {} ~Array() { delete[] data; } T& operator[](int index) { return data[index]; } private: int size; T* data; };
Function Template
Function template allows us to create functions that can be used on different data types. Likewise, it allows us to create a template that can be used to create functions with different parameter types and return value types.
template <typename T> T max(T a, T b) { return (a > b) ? a : b; }
Difference
The main difference between class templates and function templates is:
<>
notation (e.g. Array<int>
), whereas function templates are instantiated explicitly by calling the function and passing type parameters (e.g. max<int>(3, 5)
) is implicitly instantiated. Practical case
Class template: Create a Pair
class template, which stores two different types value.
template <typename K, typename V> class Pair { public: Pair(K key, V value) : key(key), value(value) {} K getKey() { return key; } V getValue() { return value; } private: K key; V value; };
We use the Pair
class template to create a Pair
object that stores integer keys and string values:
Pair<int, string> pair(1, "C++"); cout << pair.getKey() << " " << pair.getValue() << endl; // 输出:1 C++
Function template : Create a swap
function template for exchanging the order of two different types of values.
template <typename T> void swap(T& a, T& b) { T temp = a; a = b; b = temp; }
We use the swap
function template to exchange two integers:
int x = 1; int y = 2; swap(x, y); // 互换 x 和 y 的值 cout << x << " " << y << endl; // 输出:2 1
The above is the detailed content of What is the difference between class templates and function templates for C++ functions?. For more information, please follow other related articles on the PHP Chinese website!