Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning pointer to itself?

Tags:

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.

like image 608
Grigor Gevorgyan Avatar asked Jun 28 '11 11:06

Grigor Gevorgyan


People also ask

Can a function return a pointer?

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.

How does a function return a pointer value?

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.

Can we declare a function that can return a pointer to a function of the same type?

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.


2 Answers

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()()()()(); } 
like image 138
Armen Tsirunyan Avatar answered Sep 24 '22 02:09

Armen Tsirunyan


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.

like image 21
Puppy Avatar answered Sep 24 '22 02:09

Puppy