Question

I created a function which, given a list of some type T, and a predicate (a pointer to a specified function), counts how many elements in the list return true.

This works with atomic predicates (isEven,isOdd,is_less_than_42), but what should I do if I want to use it with N-ary predicates? Is there any way to pass an optional list of N-1 arguments needed by the N-ary predicate?

template<typename T, class Pred>
int evaluate(listofelements<T> &sm, Pred pred){
    typename listofelements<T>:: iterator begin, end;
    int count=0;
    begin=sm.begin();
    end=sm.end();
    while(begin!=end){
        if(pred(*(begin->data))) count++;
        begin++;
    }
    return count;
}
Was it helpful?

Solution

You could use std::bind to convert an N-ary function to a unary function object.

using std::placeholders::_1;

evaluate(sm, std::bind(some_function, _1, other, arguments));

std::bind is in C++11, but in older compilers it is likely that TR1 is included where you could use std::tr1::bind, and lastly there is still Boost.Bind.

Or you could make up the function object yourself:

struct SomeFunctor
{
    SecondType arg2;
    ThirdType arg3;
    SomeFunctor(cosnt SecondType& arg2, const ThirdType& arg3)
      : arg2(arg2), arg3(arg3)
    {}

    ResultType operator()(const FirstType& arg1) const
    {
        return some_function(arg1, arg2, arg3);
    }
};

evaluate(sm, SomeFunctor(other, arguments));
//           ^ construct SomeFunctor with arg2=other, arg3=arguments
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top