在开发中可能需要一个方法两种类型的数据去访问和使用,C++中诞生了泛型的概念,
1 #include <iostream> 2 using namespace std; 3 template <class T, int size> 4 T min(const T(&array)[size]) { 5 //寻找数组中最小的元素 6 T min_val = array[0]; 7 for (int ix = 1; ix < size; ++ix) { 8 if (array[ix] < min_val) 9 min_val = array[ix]; 10 } 11 return min_val; 12 } 13 int main() { 14 int ia[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 15 double da[5] = { 6.7, 5.7, 5.6, 9.6, 2.8}; 16 int mi = min(ia); //Type => int, size => 9 17 double md = min(da);//Type => double, size => 5 18 19 cout << "mi: " << mi << endl; 20 cout << "md: " << md << endl; 21 }
输出结果:
Java中也有类似的概念:
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Integer ia[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Double da[] = { 6.7, 5.7, 5.6, 9.6, 2.8}; int mi = min(ia,ia.length); //Type => int, size => 9 double md = min(da,da.length);//Type => double, size => 5 System.out.println("数组ia的最小元素为: " + mi + " 数组da的最小元素为: " + md); } public static <T> T min (T [] array, int size) { T min_val = array[0]; for (int ix = 1; ix < size; ++ix) { if (((Comparable)array[ix]).compareTo(min_val) == -1 ) min_val = array[ix]; } return min_val; }
执行结果如下:
//数组ia的最小元素为: 1 数组da的最小元素为: 2.8