Passing local struct to count_if

Viewed 382

I am trying to pass an anonymous struct to std::count_if, which is failing to compile.

When I try to compile (with g++ 4.5.3, not using the c++03 or c++11 extensions), I get an error in the fail() method, but the pass() method does not have that error.

In function ‘void fail()’:
Test.cpp:34:24: error: no matching function for call to ‘count_if(std::map<int, int>::iterator, std::map<int, int>::iterator, fail()::<anonymous struct>&)’

I get a similar error if I make the struct a named struct. I do not see why declaring it outside versus inside the function should make a difference. What am I missing?

#include <map>
#include <algorithm>

typedef std::map<int, int> Map;

void fail()
{
  struct {
    bool operator()(Map::value_type const& value)
    {
      return value.second > 0;
    }
  } checker;

  Map map;
  std::count_if(map.begin(),
                map.end(),
                checker);
}

struct Checker {
  bool operator()(Map::value_type const& value)
  {
    return value.second > 0;
  }
};
void pass()
{
  Map map;
  Checker checker;
  std::count_if(map.begin(),
                map.end(),
                checker);
}
2 Answers
Related