我有一个这样的向量:
typedef vector<Message*> OmciMessages;
OmciMessages omciResponses;我有一个像下面这样的函子,我怀疑这是不正确的:
class isMatching{
public:
bool operator()(const Message* responseMsg,unsigned short transactionid){
return responseMsg->getTransactionId()==transactionid;
}
};然后,我调用find_if,并希望使用函子在向量中查找某些内容,但只针对类中的特定事务处理符:
OmciMessages::iterator responseit
= find_if(omciResponses.begin(),
omciResponses.end(),
bind2nd(isMatching(),transactionid));编译器不喜欢它,并产生了相当多的错误消息,这些错误消息通常很难解释为模板类。
/repo/stuyckp/ngpon2WW/tools/cm4/tools/GNU/src/gcc/i686-pc-linux-gnu/bin/../lib/gcc/i686-pc-linux-gnu/3.4.6/../../../../../include/c++/3.4.6/bits/stl_function.h:429: error: no type named `first_argument_type' in `class isMatching'如果我在没有函数对象的情况下这样做的话,它就能工作:
static bool isMatching(Message* responseMsg){
return responseMsg->getTransactionId()==transactionid;
}
transactionid = 5; //global variable being used. yuck, don't like it
find_if(omciResponses.begin(),
omciResponses.end(),
isMatching);但是,我需要一个预先设置的全局变量事务id,我认为这并不是一个好的设计。那么,如何使用bind2nd方法来实现这一点呢?
发布于 2015-08-28 06:02:26
struct isMatching
{
unsigned short transactionid;
explicit isMatching(unsigned short transactionid) : transactionid(transactionid) {}
bool operator()(const Message* responseMsg) const
{
return responseMsg->getTransactionId() == transactionid;
}
};
std::find_if(omciResponses.begin()
, omciResponses.end()
, isMatching(0));
// ^ transactionId to be searched for演示
请注意,如果您强烈要求使用std::bind2nd,或者函数对象将是无状态的,那么根本不需要将函数对象作为单独的类:
bool isMatching(const Message* responseMsg, unsigned short transactionid)
{
return responseMsg->getTransactionId() == transactionid;
}
std::find_if(omciResponses.begin()
, omciResponses.end()
, std::bind2nd(std::ptr_fun(&isMatching), 0));
// ~~~~~~~~~~~^ ^ transactionId to be searched for
// transform to a function object演示2
发布于 2015-08-28 06:03:39
bind2nd需要函子类具有适应性,即提供某些类型,包括first_argument_type、second_argument_type和result_type。您可以在函子类中自己定义它们,也可以从函数继承它们以简化以下操作:
class isMatching : public std::binary_function<const Message*, unsigned short, bool> {
public:
bool operator()(const Message* responseMsg, unsigned short transactionid) const {
return responseMsg->getTransactionId() == transactionid;
}
};发布于 2015-08-28 06:05:49
考虑到编译器的版本,我假设C++11不是一个选项(否则答案很简单:使用lambda)。
旧函数对象绑定(在C++11中不推荐,在C++17中被删除)需要一组嵌套的类型设置。您需要将result_type、first_argument_type和second_argument_type定义为isMatching的成员,直接或通过binary_function助手(在C++11中也不推荐,在C++17中删除)来与bind2nd一起使用。
您还可以使用一个带有两个参数的普通函数,用ptr_fun来调整它(同样,在C++11中不推荐,在C++17中删除),然后用bind2nd绑定。
或者使用有状态函子,如Piotr的答案所示。
https://stackoverflow.com/questions/32264215
复制相似问题