Can we have functions inside functions in C++?

后端 未结 12 2254
抹茶落季
抹茶落季 2020-11-22 14:51

I mean something like:

int main() 
{
  void a() 
  {
      // code
  }
  a();

  return 0;
}
12条回答
  •  孤城傲影
    2020-11-22 15:33

    Local classes have already been mentioned, but here is a way to let them appear even more as local functions, using an operator() overload and an anonymous class:

    int main() {
        struct {
            unsigned int operator() (unsigned int val) const {
                return val<=1 ? 1 : val*(*this)(val-1);
            }
        } fac;
    
        std::cout << fac(5) << '\n';
    }
    

    I don't advise on using this, it's just a funny trick (can do, but imho shouldn't).


    2014 Update:

    With the rise of C++11 a while back, you can now have local functions whose syntax is a little reminiscient of JavaScript:

    auto fac = [] (unsigned int val) {
        return val*42;
    };
    

提交回复
热议问题