Created
April 13, 2012 15:02
-
-
Save eiennohito/2377485 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdafx.h" | |
#include <iostream> | |
#include <vector> | |
struct Person { | |
private: | |
int age; | |
public: | |
int getAge() const { return age; } | |
Person() { age = rand() % 100 + 1; } | |
}; | |
struct Wine { | |
private: | |
int age; | |
public: | |
int getAge() const { return age; } | |
Wine() { age = rand() % 1000 + 1; } | |
}; | |
struct Rock { | |
private: | |
long age; | |
public: | |
long getAge() const { return age; } | |
Rock() { age = rand(); } | |
}; | |
template<typename R> | |
struct Foo { | |
public: | |
template<typename T> | |
R operator()(const T& obj) { return static_cast<R>(obj.getAge()); } | |
typedef R result_type; | |
}; | |
struct IteratorIterator { | |
template<class T, typename Func> | |
typename Func::result_type average(Func foo, T collection) { | |
Func::result_type accum = 0; | |
int size = 0; | |
for (typename T::const_iterator i = collection.begin(); i != collection.end(); ++i, size++) { | |
typename T::const_reference ref = *i; | |
accum += foo(ref); | |
} | |
return accum / size; // (size * 1.0)? Не выстрелить бы в ногу при приведении типов | |
} | |
}; | |
int _tmain(int argc, _TCHAR* argv[]) | |
{ | |
std::vector<Person> persons; | |
std::vector<Wine> wine; | |
std::vector<Rock> rocks; | |
for (int i = 0; i < 10; i++) { | |
persons.push_back(Person::Person()); | |
wine.push_back(Wine::Wine()); | |
rocks.push_back(Rock::Rock()); | |
} | |
Foo<int> foo; | |
Foo<long> foo2; | |
IteratorIterator ii; | |
printf("%d\n", ii.average(foo,persons)); | |
printf("%d\n", ii.average(foo,wine)); | |
printf("%d\n", ii.average(foo2,rocks)); | |
getchar(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment