Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

c++ - Function returning pointer to itself?

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

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

1 Reply

0 votes
by (71.8m points)
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()()()()();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...