Why can't I define a function inside another function?

后端 未结 11 1898
陌清茗
陌清茗 2020-11-27 16:55

This is not a lambda function question, I know that I can assign a lambda to a variable.

What\'s the point of allowing us to declare, but not define a function insid

11条回答
  •  感动是毒
    2020-11-27 17:13

    This is not an answer to the OP question, but rather a reply to several comments.

    I disagree with these points in the comments and answers: 1 that nested declarations are allegedly harmless, and 2 that nested definitions are useless.

    1 The prime counterexample for the alleged harmlessness of nested function declarations is the infamous Most Vexing Parse. IMO the spread of confusion caused by it is enough to warrant an extra rule forbidding nested declarations.

    2 The 1st counterexample to the alleged uselessness of nested function definitions is frequent need to perform the same operation in several places inside exactly one function. There is an obvious workaround for this:

    private:
    inline void bar(int abc)
    {
        // Do the repeating operation
    }
    
    public: 
    void foo()
    {
        int a, b, c;
        bar(a);
        bar(b);
        bar(c);
    }
    

    However, this solution often enough contaminates the class definition with numerous private functions, each of which is used in exactly one caller. A nested function declaration would be much cleaner.

提交回复
热议问题