![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: May 2006
Posts: 2
Rep Power: 0
![]() |
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!
}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>&)’ 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 7:34 PM. |
|
|
|
|
|
#2 | ||
|
Expert Programmer
Join Date: Jun 2005
Posts: 850
Rep Power: 4
![]() |
You can't do it in Visual Studio either (I'm not sure why there is this restriction, but there is probably a good reason).
Quote:
Quote:
#include <set>
#include <algorithm>
namespace myNamespace
{
class comparer
{
public:
bool operator () (int a, int b) { return a < b; }
};
}
int main()
{
std::set<int> s;
s.insert(1); s.insert(2);
myNamespace::comparer comparer;
bool test = comparer(1, 2); // Works
return *( std::max_element(s.begin(), s.end(), comparer) ); // Fails!
} |
||
|
|
|
|
|
#3 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,222
Rep Power: 5
![]() |
The reason comes down to how templates are instantiated. In essence, a template can only be instantiated for types that have external linkage (in your context, they cannot be anonymous). If you want to avoid cluttering the global namespace with your algorithms, place them in a namespace of their own.
In this example, as you're using <algorithm> anyway, why not use this? return *( std::max_element(s.begin(), s.end(), std::less<int>()) ); |
|
|
|
|
|
#4 |
|
Newbie
Join Date: May 2006
Posts: 2
Rep Power: 0
![]() |
Thank you, Dark and Grumpy. When I grow up, I'll weasel my way into the ISO C++ Standards Committee and make them abolish the restriction.
Overloading operator < for my classes seems like a good solution in this case -- though I use functors for more than finding max_element(). Thanks for the idea. |
|
|
|
|
|
#5 | |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,222
Rep Power: 5
![]() |
Quote:
Last edited by grumpy; May 31st, 2006 at 1:35 AM. |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|