创建: 2020/02/03
| 模板函数 | |
|
不固定类型的函数(根据类型自动重载) template <class Ttype> 返回值类型 函数名(参数) { ... }
● Ttype是占位符, 可以在函数里用, 实际编译器实际生成函数时会换成具体的数据类型 // 也可以把class改成typename, 但一般不这样
template <typename Ttype> 返回值类型 函数名(参数) { ... }
● 可以有多个占位符 template <class Ttype1, class Ttype2, ...> 返回值类型 函数名(参数) { ... }
|
|
| 模板类 | |
| 声明与定义 |
template <class t1, class t2, ...> class 类名 {
...
}
● 模板类的函数视作模板函数, 不需要template前缀 ● 由于内部是模板函数, 所以定义放在外面时候写法要注意 template <class t1, class t2> class MyClass {
...
public:
void setA(t1 a) { ... }
}
// 在类外部定义类的方法的写法
template <class t1, class t2> MyClass<t1, t2>::setA(t1 a) { ... }
// 不一定要t1, t2, 可以换名字。只要顺序一致就行
template <class A, class B> MyClass<A, B>::setA(A a) { ... }
|
| 生成实例 |
类名 <type> 变量名;
|
| 错误处理 | |
| new运算符的错误处理 | |
来源:https://www.cnblogs.com/lancgg/p/12254522.html