如要设计一个可求得一般container中最大元素的函数,声明给定如下:
template<typename ElementType, typename ContainerType>
ElementType maxElement(ContainerType &container)
我主要不明白以下两点:
1. 如何传入container 的元素类型ElementType?
2. 在函数内如何进行对container的元素的操作?(iterator?)
答:
1. 如何传入container 的元素类型ElementType?
maxElement<int, list<int>>(l) ;在调用模板函数时候对其实例化,详见下面代码
2.是的,通过iterator操作
需要理解的是模板的实例化是在编译程序之前,由编译器自动展开的,有点类似于宏替换,只不过模板实例化提供了一些高级功能,比如模板参数的推导。
#include <iostream> #include <vector> #include <list> using namespace std; template <typename ElementType, class ContainerType> ElementType maxElement(ContainerType &container) { ContainerType::iterator iter = container.begin(); ElementType max = *iter; for (iter++; iter != container.end(); iter++) { if (*iter > max) max = *iter; } return max; } void main() { list<int> l; l.push_back(10); l.push_back(12); l.push_back(2); l.push_back(44); cout << maxElement<int, list<int>>(l) << endl; }