Templates in C++

本文介绍了C++中模板的基本概念,包括模板的工作原理、如何创建函数模板和类模板,以及它们与函数重载的区别。展示了模板在不同类型数据上的展开实例,并讨论了模板参数、默认值和特殊化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Templates in C++ - GeeksforGeeksicon-default.png?t=LA92https://www.geeksforgeeks.org/templates-cpp/

What is template

A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. 

C++为支持template引入的关键字

C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’.

How do templates work? 

Templates are expanded at compiler time. This is like macros. The difference is, the compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of same function/class.

编译时展开多个,这也是常说的使用STL代码会变大

怎样看到展开后的代码样子?

Templates are part of the language, not some pre-processor pass - they are processed by the compiler, just like other code.  (并不是像C一样预处理展开宏之后的代码)

但是可以通过

➜  c++ nm a.out | c++filt| grep myMax (证明生成了多个函数)
000000000000134f W char myMax<char>(char, char)
0000000000001323 W double myMax<double>(double, double)
0000000000001303 W int myMax<int>(int, int)

g++ -fdump-rtl-all learn_c++.cc 会生成多个文件看 以dfinish结尾的文件

其中有

;; Function myMax<int> (_Z5myMaxIiET_S0_S0_, funcdef_no=1760, decl_uid=36291, cgraph_uid=673, symbol_order=675)

;; Function myMax<double> (_Z5myMaxIdET_S0_S0_, funcdef_no=1763, decl_uid=36332, cgraph_uid=676, symbol_order=678)

;; Function myMax<char> (_Z5myMaxIcET_S0_S0_, funcdef_no=1765, decl_uid=36345, cgraph_uid=678, symbol_order=680)

虽然不能通过编译的中间文件看到 template 展开后的样子,但是通过上面的方式看到展开成多个函数是无疑的。

Function Templates

We write a generic function that can be used for different data types.

#include <iostream>
using namespace std;

// One function works for all data types. This would work
// even for user defined types if operator '>' is overloaded
template <typename T>
T myMax(T x, T y)
{
return (x > y)? x: y;
}

int main()
{
cout << myMax<int>(3, 7) << endl; // Call myMax for int
cout << myMax<double>(3.0, 7.0) << endl; // call myMax for double
cout << myMax<char>('g', 'e') << endl; // call myMax for char

return 0;
}

Class Templates

Class Templates Like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc. 
Following is a simple example of template Array class. 

#include <iostream>
using namespace std;

template <typename T>
class Array {
private:
    T *ptr;
    int size;
public:
    Array(T arr[], int s);
    void print();
};

template <typename T>
Array<T>::Array(T arr[], int s) {
    ptr = new T[s];
    size = s;
    for(int i = 0; i < size; i++)
        ptr[i] = arr[i];
}

template <typename T>
void Array<T>::print() {
    for (int i = 0; i < size; i++)
        cout<<" "<<*(ptr + i);
    cout<<endl;
}

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    Array<int> a(arr, 5);
    a.print();
    return 0;
}

Can there be more than one arguments to templates? 


Yes, like normal parameters, we can pass more than one data types as arguments to templates. The following example demonstrates the same. 

Can we specify default value for template arguments? 


Yes, like normal parameters, we can specify default arguments to templates. The following example demonstrates the same. 

What is the difference between function overloading and templates? 


Both function overloading and templates are examples of polymorphism feature of OOP. Function overloading is used when multiple functions do similar operations, templates are used when multiple functions do identical operations.


What happens when there is a static member in a template class/function? 


Each instance of a template contains its own static variable.


What is template specialization? 


Template specialization allows us to have different code for a particular data type.


Can we pass nontype parameters to templates? 


We can pass non-type arguments to templates. Non-type parameters are mainly used for specifying max or min values or any other constant value for a particular instance of a template. The important thing to note about non-type parameters is, they must be const. The compiler must know the value of non-type parameters at compile time. Because the compiler needs to create functions/classes for a specified non-type value at compile time. In below program, if we replace 10000 or 25 with a variable, we get a compiler error.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值