Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
258 views
Welcome To Ask or Share your Answers For Others

1 Answer

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()()()()();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...