c++ 模板
模板函数
模板函数例子如下:
[cpp]
#include <iostream>
template <class T>
const T& min(const T& a, const T& b) {
return a < b ? a : b;
}
int main()
{
int x = 10, y = 20;
long xLong = 100, yLong = 200;
int minimum = min<int>(x, y);
long minimumLong = min<long>(xLong,yLong);
std::cout << "minimum = " << minimum << std::endl;
std::cout << "minimumLong = " << minimumLong << std::endl;
}
模板函数也能向普通函数一样声明为inline的,需要特殊说明的是其需要注意inline关键字的位置,不能将关键字放到template的前面如下所示:
template <class T>
inline const T& min(const T& a,const T& b) {
但不能这样:
inline template <class T>
const T& min(const T& a, constT& b) {
模板类
模板类的示例代码如下:
[cpp]
template <class T>
class Complx {
private:
T real, imag;
public:
Complx(T&, T&);
T& getReal();
T& getImag();
};
template <class T>
Complx<T>::Complx(T& a, T& b) {
real = a;
imag = b;
}
template <class T>
T& Complx<T>::getReal() {
return real;
}
template <class T>
T& Complx<T>::getImag() {
return imag;
}
#include <iostream>
int main()
{
double i=100, j=200;
Complx <double> myComplx(i,j);
std::cout <<"My complex is " << myComplx.getReal() << ","
<< myComplx.getImag() << std::endl;
}
补充:软件开发 , C++ ,