Why C++ does not allow function parameters used for default values latter parameters?

天大地大妈咪最大 提交于 2019-12-01 16:00:38

问题


This is a follow-up on this question. The code in the OP question there looked quite reasonable and unambiguous to me. Why does not C++ allow using former parameters to define default values of latter parameters, something like this:

int foo( int a, int b = a );

Also, at least in C++11 declared types of parameters can be used to determine the return type, so it's not unheard of to use function parameters in similar manner:

auto bar( int a ) -> decltype( a );

Thus the question: what are the reason(s) why the above declaration of foo is not allowed?


回答1:


For one thing, this would require that a is evaluated before b, but C++ (like C) does not define the order of evaluation for function parameters.

You can still get the effect you want by adding an overload:

int foo(int a, int b)
{ /* do something */ }

int foo(int a)
{ return foo(a, a); }


来源:https://stackoverflow.com/questions/31713217/why-c-does-not-allow-function-parameters-used-for-default-values-latter-parame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!