[英]Why C++ does not allow function parameters used for default values latter parameters?
This is a follow-up on this question . 这是对这个问题的后续跟进。 The code in the OP question there looked quite reasonable and unambiguous to me.
OP问题中的代码看起来非常合理且对我来说毫不含糊。 Why does not C++ allow using former parameters to define default values of latter parameters, something like this:
为什么C ++不允许使用以前的参数来定义后面的参数的默认值,如下所示:
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: 此外,至少在C ++ 11中,声明的参数类型可用于确定返回类型,因此以类似的方式使用函数参数并非闻所未闻:
auto bar( int a ) -> decltype( a );
Thus the question: what are the reason(s) why the above declaration of foo
is not allowed? 因此,问题是:为什么不允许上述
foo
声明的原因是什么?
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. 一方面,这将需要
a
被之前评估b
,但C ++(如C)没有定义评估顺序为函数参数。
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); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.