Is it possible in C++ to write a function that returns a pointer to itself?
If no, suggest some other solution to make the following syntax work:
some_type f () { static int cnt = 1; std::cout << cnt++ << std::endl; } int main () { f()()()...(); // n calls }
This must print all the numbers from 1 to n
.
We can pass pointers to the function as well as return pointer from a function. But it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns.
Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.
You cannot return a function in C - you return a pointer to a function. If you mean to define a function which returns a pointer to a function which again returns a pointer to a function and so on, then you can use typedef to implement it.
struct function { function operator () () { //do stuff; return function(); } }; int main() { function f; f()()()()()(); }
You can choose to return a reference to function if needed and return *this
;
Update: Of course, it is syntactically impossible for a function of type T
to return T*
or T&
Update2:
Of course, if you want one to preserve your syntax... that is
some_type f() { }
Then here's an Idea
struct functor; functor f(); struct functor { functor operator()() { return f(); } }; functor f() { return functor(); } int main() { f()()()()(); }
No, you can't, because the return type has to include the return type of the function, which is recursive. You can of course return function objects or something like that which can do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With