Humam Helfawi Humam Helfawi - 1 year ago 70
C++ Question

Comparer that takes the wanted attribute

In order to use a standard function like

on some standard container

struct T{
int x,y;

based on the
value, you need to write something like (for example):

std::vector<T> v;
//fill v
std::sort(v.begin(),v.end(),[](const auto& l,const auto& r){
return l.y<r.y;

The comparer that was written as lambda function is used too much and re-written again and again during the code for various classes and attributes.

Considering the case where
's type is comparable (either like
or there is an overload for the
< operator
), is there any way to achieve something like:

std::sort(v.begin(),v.end(),imaginary::less(T::y)); // Imaginary code

Is it possible in C++ to write such a function like
? or anything similar?

I am asking because I remember something like that in some managed language (I am not sure maybe C# or Java). However, I am not sure even about this information if it is true or not.

Answer Source
template<typename T, typename MT>
struct memberwise_less
    MT T::* const mptr;
    auto operator()(const T& left, const T& right) const
    { return (left.*mptr) < (right.*mptr); }

template<typename T, typename MT>
memberwise_less<T, MT> member_less(MT T::*mptr)
    return { mptr };

and then you can do

std::sort(v.begin(), v.end(), member_less(&T::y));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download