#include <iostream>
using namespace std;
//functors
struct Iter_less_iter
{
template <typename iter1, typename iter2>
bool operator() (iter1 it1, iter2 it2) const
{
return *it1 < *it2;
}
};
Iter_less_iter less_iter()
{
return Iter_less_iter();
};
template <typename _ForwardInterator, typename Compare>
_ForwardInterator _max_element_T(_ForwardInterator first, _ForwardInterator last, Compare comp)
{
if (first == last)
{
return first;
}
_ForwardInterator result = first;
while (++first != last)
{
if (comp(result, first))
{
result = first;
}
}
return result;
}
template <typename _ForwardInterator>
_ForwardInterator max_element_T(_ForwardInterator first, _ForwardInterator last)
{
return _max_element_T(first, last, less_iter());
}
template <typename T>
T maxT(std::initializer_list<T> lst)
{
return *max_element_T(lst.begin(), lst.end());
}
int main()
{
cout << maxT({ 23,12,45,55,78,17,34,43 }) << endl;
system("pause");
return 0;
}
执行结果: 78
利用可变参数模板的思想重新设计max函数,实际写代码过程中发现使用initializer_list也可以完美解决问题。