栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Templates in C++

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Templates in C++

Templates in C++ - GeeksforGeekshttps://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)
0000000000001323 W double myMax(double, double)
0000000000001303 W int myMax(int, int)

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

其中有

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

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

;; Function myMax (_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
using namespace std;

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

int main()
{
cout << myMax(3, 7) << endl; // Call myMax for int
cout << myMax(3.0, 7.0) << endl; // call myMax for double
cout << myMax('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
using namespace std;

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

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

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

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    Array 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.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/588600.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号