is it possible in C or C++ to create a function inside another?

后端 未结 15 2013
迷失自我
迷失自我 2020-12-15 09:18

Could someone please tell me if this is possible in C or C++?

void fun_a();
//int fun_b();
...
main(){
   ...
   fun_a();
   ...
   int fun_b(){
     ...
            


        
15条回答
  •  误落风尘
    2020-12-15 09:48

    Wow, I'm surprised nobody has said yes! Free functions cannot be nested, but functors and classes in general can.

    void fun_a();
    //int fun_b();
    ...
    main(){
       ...
       fun_a();
       ...
       struct { int operator()() {
         ...
       } } fun_b;
    
       int q = fun_b();
       ...
    }
    

    You can give the functor a constructor and pass references to local variables to connect it to the local scope. Otherwise, it can access other local types and static variables. Local classes can't be arguments to templates, though.

提交回复
热议问题