0

我创建了一个函数,给定一个 T 类型的列表和一个谓词(指向指定函数的指针),计算列表中有多少元素返回 true。

这适用于原子谓词(isEven、isOdd、is_less_than_42),但如果我想将它与 N 元谓词一起使用,我该怎么办?有没有办法传递 N 元谓词所需的 N-1 个参数的可选列表?

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;
}
4

1 回答 1

1

您可以使用std::bind将 N 元函数转换为一元函数对象。

using std::placeholders::_1;

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

std::bind在 C++11 中,但在较旧的编译器中,很可能在您可以使用的地方包含 TR1 std::tr1::bind,最后还有 Boost.Bind。

或者你可以自己组成函数对象:

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
于 2012-02-10T08:35:58.790 回答