Why should default parameters be added last in C++ functions?

前端 未结 9 1588
轻奢々
轻奢々 2020-11-27 07:01

Why should default parameters be added last in C++ functions?

相关标签:
9条回答
  • 2020-11-27 07:54

    Its because it uses the relative position of arguments to find to which parameters they correspond.

    It could have used the types to identify that an optional parameter was not given. But implicit conversion could interfere with it. Another problem would be programming errors that could be interpreted as optional arguments drop out instead of missing argument error.

    In order to allow any argument to become optional, there should be a way to identify the arguments to make sure there is no programming error or to remove ambiguities. This is possible in some languages, but not in C++.

    0 讨论(0)
  • 2020-11-27 07:56

    As a general rule function parameters are processed by the compiler and placed on the stack in right to left order. Therefore it makes sense that any parameters with default values should be evaluated first.

    (This applieds to __cdecl, which tends to be the default for VC++ and __stdcall function declarations).

    0 讨论(0)
  • 2020-11-27 07:58

    As most of the answers point out, having default parameters potentially anywhere in the parameter list increases the complexity and ambiguity of function calls (for both the compiler and probably more importantly for the users of the function).

    One nice thing about C++ is that there's often a way to do what you want (even if it's not always a good idea). If you want to have default arguments for various parameter positions, you can almost certainly do this by writing overloads that simply turn around and call the fully-parameterized function inline:

     int foo( int x, int y);
     int foo( int y) {
         return foo( 0, y);
     }
    

    And there you have the equivalent of:

     int foo( int x = 0, int y);
    
    0 讨论(0)
提交回复
热议问题