Cpp-泛型编程基础
2018-01-27 17:26
225 查看
Cpp-泛型编程基础
哇,很久没有写cpp了,写得太挫了,主要是。emm,好像数据结构作业是实现线程池,趁此机会好好学一遍cpp吧,不要再吹水了。只希望。C++是一门很强大的语言,泛型编程一般来说可望而不可及,今天来啃一下这小基础吧。
函数重载
假设要比较两个数的值,我们可以使用两个函数进行重载:int compare(const int&a, const int&b) { if (a == b) return 0; return a>b ? 1 : -1; } int compare(const double&a, const double&b) { if (a == b) return 0; return a > b ? 1 : -1; }两个函数基本相同,唯一不同的是函数的参数,但是这种比较麻烦。也比较容易出错。
所以对于不同类型都需要用这个函数,我们就产生了这个模板。
模板的定义
template <typename T> int compare(const T &v1, const T &v2) { if (v1 < v2) return 1; else return 0; }模板的定义以关键字 template开始,后面接着模板参数,模板的形参是用尖括号或者多个模板形参,形参之间用逗号进行分割。
使用函数模板
使用函数模板的时候,编译器推断是哪个模板实参绑定到模板形参。一旦编译器确定了实际的模板实参,也就是实例化了函数模板的实例
std::cout << compare(1, -1)<<std::endl;
inline函数模板
函数模板可以用非函数模板一样的声明为Inline,说明符号放在模板形参表之后,返回类型之前,不能放在关键字template之前。template <typename T> inline T min(const T&a, const T&b) { return a > b ? b : a; }
定义类模板
当我们定义类的模板的时候同使用函数模板是一样的。定义一个Point类,可能是2D,也有可能是3D,所以需要类模板,第一种定义是3d的Point
template<class type> class Point3d { public: Point3d(type x = 0.0, type y = 0.0, type z = 0.0) :_x(x), _y(y), _z(z){} type x() { return _x; } void x(type xval) { _x = xval; } private: type _x; type _y; type _z; };或者我们也可以变成
template <class type,int dim> class Point { public: Point(); Point(type coords[dim]) { for (int index = 0; index < dim; index++) { _coords[index] = coords[index]; } } type& operator[](int index) { assert(index < dim&&index >= 0); return _coords[index]; } type operator[](int index) const { assert(index < dim&&index >= 0); return _coords[index]; } private: type _coords[dim]; };这样就可以,然后直接声明这个就可以进行调用:
Point<int, 3> point;
相关文章推荐
- CPP-基础:快速排序
- CPP入门基础知识
- CPP入门基础知识
- CPP-基础:内存泄露及其检测工具
- C++模板与泛型编程基础
- CPP-基础:关于引用
- CPP-基础:windows api 多线程---互斥量、信号量、临界值、事件区别
- cpp 基础
- json2jsoncpp 基础应用篇
- c++模板与泛型编程基础
- CPP-基础:C_C++变量命名规则
- [C++]cpp小笔记3 --- C++基础类型的大小和转换
- CPP-基础:内部函数应该在当前源文件中说明和定义
- CPP-基础:信号量
- CPP-基础:函数指针,指针函数,指针数组
- c++基础——模板和泛型编程
- c++模板与泛型编程基础
- CPP-基础:关于私有成员的访问
- CPP入门基础知识(一)
- 《Java编程思想第四版》笔记---15章(1) 泛型编程基础