Boost logo

Boost :

From: Maciej Sobczak (maciej_at_[hidden])
Date: 2002-07-25 02:38:19

Maciej Sobczak wrote:
> Some time ago I wrote the adaptor class that allows you to wrap
> *arbitrary* functor (less, greater, etc.) in a uniform manner:

Of course, forgot to mention: that adaptor was for different, specific
The one for sorting (for operations on two aggregate objects) can look
like here (with complete test program, stripped from #includes):

template <class T, typename M, class OP>
class oper_on_mem_t : binary_function<T, M, bool>
        explicit oper_on_mem_t(M T:: *m, OP op) : m_(m), op_(op) {}
        bool operator()(const T &lhs, const T &rhs) const
                return op_(lhs.*m_, rhs.*m_);
        M T::* m_;
        OP op_;

template <class T, typename M, class OP>
oper_on_mem_t<T, M, OP> oper_on_mem(M T:: *m, OP op)
        return oper_on_mem_t<T, M, OP>(m, op);

struct S { int a, b, c; };

int main ()
        S s1 = {1,2,3};
        S s2 = {3,1,2};
        S s3 = {2,3,1};

        vector<S> v;

        sort(v.begin(), v.end(), oper_on_mem(&S::a, less<int>()));

        for (vector<S>::iterator i = v.begin(); i != v.end(); ++i)
                cout << "(" << i->a << ", " << i->b
                        << ", " << i->c << ")" << endl;

        return 0;

(1, 2, 3)
(2, 3, 1)
(3, 1, 2)

The motivation is to write the adaptor that will be able to accommodate
different needs, so that users will be able to use it uniformly with
different, supplied operations. This allows also to write generic code
that is independent of the actually provided comparison functor.

Functors like less_element or greater_element cannot achieve this.

Does Boost have something similar to this?


Maciej Sobczak

Boost list run by bdawes at, gregod at, cpdaniel at, john at