Function returning pointer to itself?

前端 未结 4 1768
闹比i
闹比i 2020-12-28 14:35

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:

som         


        
相关标签:
4条回答
  • 2020-12-28 15:15

    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.

    0 讨论(0)
  • 2020-12-28 15:18
    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()()()()();
    }
    
    0 讨论(0)
  • 2020-12-28 15:19

    You can use pattern of function objects:

    struct f
    {
      f& operator () ()
      {
        static int cnt = 1;
        cout<<cnt++<<endl;
        return *this;
      }
    };
    

    Just you need to put one extra (). Usage:

    f()()()(); //prints 1,2,3
    

    Here is the demo.

    0 讨论(0)
  • 2020-12-28 15:19

    Of course it is possible, just look the following code:

    
    #include <stdio.h>
    
    typedef void * (*func)();
    
    void * test()
    {
        printf("this is test\n");
        return (void *)&test;
    }
    
    int main()
    {
        (*(func)test())();
    }
    

    The result is :

    
    user@linux:~/work/test> gcc test_func.cc -o test          
    user@linux:~/work/test> ./test
    this is test
    this is test
    
    0 讨论(0)
提交回复
热议问题