On Feb 8, 10:57 am, suresh shenoy <msureshshe...@gmail.com> wrote:
Hello,
I came across a snippet of code which I was not able to interpre=
correctly.
typedef CategoryStream& (*cspf) (CategoryStream&);
CategoryStream& CategoryStream::operator<< (cspf pf) {
return (*pf)(*this);
}
If anyone could explain each line, it would be great!
#include <iostream>
using namespace std;
class CategoryStream;
/*
cspf is the name of a type. That type is a function pointer. That
type
can point to any function that takes a reference to CategoryStream
and
returns a reference CategoryStream.
Note: It is highly likely that the function returns the parameter
that it
takes.
*/
typedef CategoryStream& (*cspf) (CategoryStream&);
/*
This function can be pointed to by a cspf, because it takes a
reference
to CategoryStream, and returns a reference to a CategoryStream:
*/
CategoryStream & foo(CategoryStream & param)
{
/*
Normally, this function is expected to do something to param.
This is
similar to sending hex to cout as in
cout << hex;
*/
cout << "in foo\n";
return param;
}
class CategoryStream
{
public:
CategoryStream & operator<< (cspf);
};
// Here is how one might use foo:
void bar()
{
CategoryStream stream;
// ignoring the return value here
foo(stream);
}
CategoryStream& CategoryStream::operator<< (cspf pf)
{
cout << "in operator<<\n";
return (*pf)(*this);
}
int main()
{
CategoryStream stream;
stream << foo;
/*
Because operator<< returns a reference to CategoryStream, we c=
I think you have explained it quite well :) . Why use typedef and not