Hi folks
While going through sample shared_ptr example in Boost tutorial, I encountered a code such as one below:
struct Foo
{
Foo( int _x ) : x(_x) {}
~Foo() { std::cout << "Destructing a Foo with x=" << x << "\n"; }
int x;
};
typedef boost::shared_ptr<Foo> FooPtr;
struct FooPtrOps
{
bool operator()( const FooPtr & a, const FooPtr & b )
{ return a->x > b->x; } // 1 (see below)
void operator()( const FooPtr & a )
{ std::cout << a->x << "\t";} // 2 (see below)
};
The FooPtrOps is then used in main as such:
int main()
{
std::vector<FooPtr> foo_vector;
std::set<FooPtr,FooPtrOps> foo_set;
....
// I then added some code to insert values
for(int i = 0; i < 100; i++)
{
FooPtr tmpNewPtr(new Foo(i));
foo_vector.push_back(tmpNewPtr);
foo_set.insert(tmpNewPtr);
}
// Print 'em
std::cout << "foo_vector:\n";
std::for_each( foo_vector.begin(), foo_vector.end(), FooPtrOps() );
std::cout << "\nfoo_set:\n";
std::for_each( foo_set.begin(), foo_set.end(), FooPtrOps() );
std::cout << "\n";
return 0;
}
So my question is:
How is the functor FooPtrOps( ) managing to print using the 1 & 2 above? Particularly using the "operator()" function? I thought that it instead should have had been defined such:
friend ostream& operator<<(ostream& os_out, const FooPtr& foo_out)
{
os_out << foo_out->x << "\t";
}
because, it defines what "<<" means for a type FooPtr. Right?
Any help is appreciated. Thanks!
[Edited by - setiz1 on September 11, 2009 2:08:13 AM]