Skip to content

Instantly share code, notes, and snippets.

@mizutomo
Created June 6, 2011 14:08
Show Gist options
  • Save mizutomo/1010332 to your computer and use it in GitHub Desktop.
Save mizutomo/1010332 to your computer and use it in GitHub Desktop.
C++ template with functor
#include <vector>
#include <algorithm>
#include <iostream>
class Hage
{
public:
float val;
Hage() {}
Hage(float _val) { val = _val; }
};
template <class T>
class Cmp
{
private:
T hoge;
public:
bool operator()(const T& a, const T& b);
};
template<class T> bool Cmp<T>::operator()(const T& a, const T& b)
{
if (a.val < b.val) {
return true;
} else {
return false;
}
}
int main()
{
Cmp<Hage> cmp_obj;
std::vector<Hage> nums;
for (int i = 5; i > 0; i--) {
nums.push_back(Hage(static_cast<float>(i + 0.5f)));
}
std::sort(nums.begin(), nums.end(), cmp_obj);
for (std::vector<Hage>::iterator iter = nums.begin(); iter != nums.end(); iter++) {
std::cout << iter->val << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment