模板(template)是泛型编程的基础,"泛型"的含义就是没有不依赖具体的数据类型.模板的引入是为了创建一般性的类(模板类)或者函数(模板函数).典型的容器比如迭代器/算法等是泛型编程的典型案例.例如,定义了一个vector,可以使用vector
函数模板
模板函数的一般定义方式为: 这里的type可以看做是代表了一种数据类型的占位符名称, 在函数内部的定义中可以使用它.
template <class type> ret-type func-name(parameter list){
// body of function
}
举例分析如下. 注意,typename关键词和class关键词的作用是相同的,class关键词会让你产生是否定义的type只能是类,而不能是其他的数据类型? 为了避免这个歧义,这里引入了typename!!!
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 template <typename T>
7 inline T const& Max (T const& a, T const& b){
8 return a < b ? b:a;
9 }
10
11 int main() {
12
13 int i = 39;
14 int j = 20;
15 cout << "Max(i, j)" << Max(i, j) << endl; # Max(i,j): 39
16
17 double f1 = 13.5;
18 double f2 = 20.7;
19 cout << "Max(f1, f2)" << Max(f1, f2) << endl; # Max(f1, f2): 20.7
20
21 string s1 = "Hello";
22 string s2 = "World";
23 cout << "Max(s1, s2)" << Max(s1, s2) << endl; # Max(s1, s2): World
24
25 return 0;
26
27 }
类模板
就像我们定义函数模板一样, 这里也可以定义类模板. 声明类模板的一般形式为:
template <class type>
class class-name{
}
举例:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T>
class Stack {
private:
vector<T> elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const{ // return true if empty.
return elems.empty();
}
};
template <class T>
void Stack<T>::push (T const& elem) {
// append copy of passed element
elems.push_back(elem);
}
template <class T>
void Stack<T>::pop () {
if (elems.empty()) {
throw out_of_range("Stack<>::pop(): empty stack");
}
// remove last element
elems.pop_back();
}
template <class T>
T Stack<T>::top () const {
if (elems.empty()) {
throw out_of_range("Stack<>::top(): empty stack");
}
// return copy of last element
return elems.back();
}
int main() {
try {
Stack<int> intStack; // stack of ints
Stack<string> stringStack; // stack of strings
// manipulate int stack
intStack.push(7);
cout << intStack.top() <<endl; // 7
// manipulate string stack
stringStack.push("hello");
cout << stringStack.top() << std::endl; // hello
stringStack.pop();
stringStack.pop();
}catch (exception const& ex) {
cerr << "Exception: " << ex.what() <<endl; // Exception: Stack<>::pop(): empty stack
return -1;
}
}
参考:
[1] C++ Templates: https://www.tutorialspoint.com/cplusplus/cpp_templates.htm
原文链接: https://www.cnblogs.com/zhao441354231/p/6025856.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/243344
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!