3

Calling

std::count_if(vec.begin(), vec.end(), std::bind2nd(std::ptr_fun(foo), 17)) 

works fine with

bool foo(int, int),

but I can't make it work with

bool foo(const int &, const int &)

Is there a way to make that work or do I have to write my own adaptor function?

Puppy
  • 138,897
  • 33
  • 232
  • 446
Michael
  • 1,302
  • 1
  • 14
  • 36
  • Why do you want to pass int's by const reference anyways? Any POD-type can be put on stack with no downsides. – Dark Jul 25 '11 at 12:32
  • It is not about int's in particular. I have more complex objects in mind – Michael Jul 26 '11 at 08:04

1 Answers1

2

The second argument is a number, and cannot be converted to const int &.

You can use boost::bind to do the trick:

std::count_if (vec.begin(), vec.end(), boost::bind (foo, _1, 17));

EDIT:

As of my first response, yes, you cannot use a variable instead of the number. I think the problem is bind2nd and ptr_fun not being properly defined to dereference the type in the case it is a reference when ptr_fun builds the internal Operation object, so ither go with boost or write your own functor class.

Diego Sevilla
  • 27,060
  • 3
  • 52
  • 82
  • 1
    This doesn't make any difference. The error is: ‘typename _Operation::result_type std::binder2nd<_operation>::operator()(typename _Operation::first_argument_type&) const [with _Operation = std::pointer_to_binary_function]’ cannot be overloaded with ‘typename _Operation::result_type std::binder2nd<_operation>::operator()(const typename _Operation::first_argument_type&) const [with _Operation = std::pointer_to_binary_function]’ – Michael Jul 25 '11 at 08:49