View Single Post
Old May 30th, 2006, 8:09 PM   #1
manannan
Newbie
 
Join Date: May 2006
Posts: 2
Rep Power: 0 manannan is on a distinguished road
Using internal classes in STL functions

When using the STL, I'd often want to instantiate an anonymous functor -- something like this:
#include <set>
#include <algorithm>

int main()
{
  std::set<int> s;
  s.insert(1); s.insert(2);

  class
  {
  public:
    bool operator () (int a, int b) { return a < b; }
  } comparer;

  bool test = comparer(1, 2); // Works
  return *( std::max_element(s.begin(), s.end(), comparer) ); // Fails!
}
The problem is, under gcc, this fails with the error
test.cpp:17: error: no matching function for call to ‘max_element(std::_Rb_tree_const_iterator<int>, std::_Rb_tree_const_iterator<int>, main()::<anonymous class>&)’
Looking at the <algorithm> header, I say that the error message makes no sense, and the program should compile just fine.
Now it seems that the only way for me to use a functor is to make its class global. But isn't there a way to somehow avoid cluttering the global namespace and keep the code beautiful? Or should I report a bug in the gcc? :-)

Last edited by manannan; May 30th, 2006 at 8:34 PM.
manannan is offline   Reply With Quote