First off, you need to make sure that your comparison class is known when you use it: moving the definition of MyComparator
in front of the definition of countNames()
would be my first step. That said, bind2nd()
wants to know the function objects it is dealing with a bit better than you what you offer: it generally wants to know the result_type
, the first_argument_type
, and the second_argument_type
. You can either get these by from std::binary_function<bool, CFileType const*, std::string const&>
or by explicitly defining them. Although I don't think it is required, you might want to make the function call operator const
. On the other hand, if you are defining a function object rather than a function (for which you could get the necessary typedef
s using std::ptr_fun()
; personally I think the name is intended to somehow make these guys appealing because it certainly isn't much fun when you have to use them), you can just go the entire way and not meddle with binders in the first place:
class MyComparator {
public:
MyComparator(std::string const& value): value_(value) {}
bool operator()(CFileType const* obj) const {
return obj->getName() == this->value_;
}
private:
std::string value_;
};
...
std::count_if(files.begin(), files.end(), MyComparator(name));
You can get roughly the same effect using binders when defining a function and binding it. Typeically, I get it wrong when I don't try out the code but it would look something like this:
bool myComparator(CFileType const* obj, std::string name) {
return obj->getName() == name;
}
...
std::count_if(files.begin(), files.end(),
std::bind2nd(std::ptr_fun(myComparator), name));
If you feel you want to pass the name
argument by reference rather than copying it all the time, you won't be able to use std::bind2nd()
, at least not unless you use a C++ 2011 compiler: it would create a type which has to consecutive const
keywords which the compiler won't like. You can use e.g. boost::bind()
which doesn't have this problem:
std::count_if(files.begin(), files.end(), boost::bind(myComparator, _1, name));
... and change the declaration of the name
parameter to be std::string const& name
.