C++模板编程指南:泛型编程基石与函数/类模板实战
模板是泛型编程基石:编写与具体类型无关的代码。模板是创建泛型类/函数的蓝图/公式。STL容器(如vector)、迭代器、算法皆基于模板。单一定义vector,可实例化vector<int>、vector<string>等无数变体。
函数模板
通用形式:
template <class type> ret-type func-name(parameter list) { /* body */ }
type为占位类型名,函数体内可用。示例:返回两值中较大者:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
inline T const& Max(T const& a, T const& b) {
return a < b ? b : a;
}
int main() {
int i=39, j=20;
cout << "Max(i, j): " << Max(i, j) << endl; // 39
double f1=13.5, f2=20.7;
cout << "Max(f1, f2): " << Max(f1, f2) << endl; // 20.7
string s1="Hello", s2="World";
cout << "Max(s1, s2): " << Max(s1, s2) << endl; // World
return 0;
}
类模板
通用形式:
template <class type> class class-name { ... }
type为占位类型,实例化时指定。可用逗号分隔定义多类型参数。示例:泛型栈Stack<T>:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <string>
#include <stdexcept>
using namespace std;
template <class T>
class Stack {
private:
vector<T> elems;
public:
void push(T const& elem) { elems.push_back(elem); }
void pop() {
if(elems.empty()) throw out_of_range("Stack<>::pop(): empty stack");
elems.pop_back();
}
T top() const {
if(elems.empty()) throw out_of_range("Stack<>::top(): empty stack");
return elems.back();
}
bool empty() const { return elems.empty(); }
};
int main() {
try {
Stack<int> intStack;
Stack<string> stringStack;
intStack.push(7);
cout << intStack.top() << endl; // 7
stringStack.push("hello");
cout << stringStack.top() << endl; // hello
stringStack.pop();
stringStack.pop(); // 触发异常
} catch(exception const& ex) {
cerr << "Exception: " << ex.what() << endl;
return -1;
}
return 0;
}
输出:7、hello、Exception: Stack<>::pop(): empty stack
C语言
- 深入理解 C++ 数据类型:基础类型、修饰符与最佳实践
- 深入理解 C++ 类型转换:隐式、显式转型与现代 Cast 算符
- 掌握 C++ 运算符:六大类型全解析与实战示例
- C++ 注释最佳实践:编写可读、可维护代码的注释艺术
- C++构造函数详解:默认、参数化与拷贝构造函数
- C++ 类模板实战指南:编写灵活的类型无关代码
- C++编程语言:核心特性全景解析
- C++常量与字面量完全手册:类型、语法与最佳实践
- C++运算符大全:算术/关系/逻辑/位/赋值/杂项与优先级结合性
- C++数值类型实战指南:基本类型、数学函数与随机数生成
- C++引用详解:核心概念、与指针三大差异及函数参数/返回值应用
- C++预处理器指令详解:#define宏、条件编译、#/#运算符与预定义宏