为什么C ++不允许将函数参数用作默认值? [英] Why C++ does not allow function parameters used for default values latter parameters?

查看:135
本文介绍了为什么C ++不允许将函数参数用作默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有关此问题的后续操作.在我看来,OP问题中的代码非常合理且毫不含糊.为什么C ++不允许使用前一个参数来定义后一个参数的默认值,例如:

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 );

此外,至少在C ++ 11中,可以使用声明的参数类型来确定返回类型,因此以类似的方式使用函数参数并非鲜见:

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 );

问题是:为什么不允许上述foo声明的原因是什么?

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

推荐答案

一方面,这要求ab之前进行求值,但是C ++(如C)未定义函数求值的顺序参数.

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); }

这篇关于为什么C ++不允许将函数参数用作默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆