Passing local structure to count_if

I am trying to pass an anonymous structure to std :: count_if, which does not compile.

When I try to compile (with g ++ 4.5.3, without using the C ++ 03 or C ++ 11 extensions), I get an error in the method fail(), but the method pass()does not have this 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 create a structure called struct. I don’t understand why declaring it outside and inside the function should matter. 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);
}
+4
source share
2 answers

According to the C ++ 03 specification, it is not allowed to use local types as template parameters. This restriction was removed with the revision of the 2011 C ++ version.

. , .

+3

++ 03, ++ 98, / ( STL)

-std=c++11

. ++ 11 FAQ

++ 11, - std::count_if

0

All Articles