"Alex said:
Hello. I would like a simpler way to do something like this:
class C {
...
bool operator<(const C&) const;
};
int main()
{
std::vector<C*> v;
...
C* x = max_element(v.begin(),v.end());
You forgot to dereference the iterator above...
}
without having to write this:
bool operator<(const C* a, const C* b)
{ return *a<*b; }
I don't know if you would consider this simpler.
class C { };
bool operator<( const C& lhs, const C& rhs );
int main() {
vector<C*> v;
C* x = *max_element( v.begin(), v.end(),
f_gx_gy( less<C>(), ptr_deref<C>() ) );
}
The above calls, ptr_deref<C>() on two C* objects, then sends the C
objects they contain to less<C>() for comparison...
To do the above, you need:
template <typename T>
struct ptr_deref: public std::unary_function<T*,T>
{
T& operator()(T* t ) const {
return *t;
}
};
template <typename Op1, typename Op2>
class f_gx_gy_t: public std::binary_function<
typename Op2::argument_type, typename Op2::argument_type,
typename Op1::result_type>
{
Op1 fn1;
Op2 fn2;
public:
f_gx_gy_t() { }
f_gx_gy_t(const Op1& f, const Op2& g): fn1(f), fn2(g) { }
typename Op1::result_type operator()(
const typename Op2::argument_type& x,
const typename Op2::argument_type& y) const
{
return fn1(fn2(x), fn2(y));
}
};
template <typename Op1, typename Op2>
inline f_gx_gy_t<Op1, Op2, Op2> f_gx_gy(const Op1& f, const Op2& g) {
return f_gx_hy_t<Op1, Op2>(f, g);
}
Yes, you have these two classes and a function but it saves you quite a
bit because you can build any function that compares two pointers...
f_gx_gy( equal_to<C>(), ptr_deref<C>() );
f_gx_gy( not_equal_to<C>(), ptr_deref<C>() ) );
f_gx_gy( greater<C>(), ptr_deref<C>() ) );
and so on...