"softcoder" <ms*****@gmail. comwrote in message
news:11******** *************@j 72g2000cwa.goog legroups.com
>
Vyacheslav Kononenko wrote:
>On Dec 14, 10:57 pm, benben <benhonghatgmai ldotcom@nospamw rote:
>>How do you declare a function f that takes a parameter that is a
pointer to itself?
So you can do f(f);
Pardon my curiosity!
Ben
struct Boo { template<class T>Boo( T ); };
void f( Boo );
void foo()
{
f( f );
}
Pardon my curiosity! but can anybody please explain why this code
works?
-softcoder
Does it? At least on my compiler, it fails to link. This is easily corrected
with a couple of empty definitions, but it still doesn't give the results
one might want.
struct Boo { template<class T>Boo( T ); };
which I would re-write as:
struct Boo
{
template<class T>
Boo( T );
};
gives Boo a templated constructor. You can pass Boo's constructor an
argument of any type and a constructor that takes that type will be produced
by the template mechanism. Thus, when you pass it f, the template parameter
T becomes f.
void f( Boo );
defines f to accept a Boo parameter. Thus when
f(f);
is called, f is converted to a Boo temporary using Boo's templated
constructor and this Boo temporary is passed to f (or at least it would be
if the compiler didn't optimise it away).
Accordingly, while f is used as the function argument, the f function never
gets to see this argument, which rather defeats the purpose (at least you
would think so; the OP didn't explain the purpose beyond satisfying his
curiousity).
Observe that recursive functions call themselves without needing a function
pointer to themselves, so it is not clear what the point of
f(f);
might be.
With function objects, you can achieve something that "works" after a
fashion:
struct F
{
F() : count(0)
{}
void operator()(F& f)
{
cout << "f\n";
++count;
if(count < 10)
f(*this);
}
int count;
};
int main()
{
F f;
f(f);
return 0;
}
--
John Carson