函数调用作为默认参数 - 可以在封装中使用其他参数吗?
假设我有以下函数,代码中的许多其他函数都需要它生成的值:
float mean(foo param1, bar param2);
我的其他函数如下所示:
float foobar(foo param1, bar param2, float meanValue);
我想要做的是:
float foobar(foo param1, bar param2, float meanValue = mean(param1, param2));
虽然将函数作为默认参数传递是合法的,但编译器 (VS2008) 抱怨 param1 和 param2 未声明 - 因为参数从 meanValue 开始从右到左推入堆栈>。当然,我不能颠倒参数的顺序,因为在这种情况下我将无法为第一个参数指定默认值。
我可以传入一些值,例如 -10000 作为平均值,告诉自己调用mean()函数;或者我可以重载每个函数(有 10 多个函数需要重载),但这不是很简洁。我认为您可以将函数作为默认参数调用,这真的很酷,我想知道是否有一种巧妙的方法来完成我想要做的事情。
Suppose I have the following function, the value it produces is needed by many other functions in the code:
float mean(foo param1, bar param2);
My other functions look like this:
float foobar(foo param1, bar param2, float meanValue);
What I want to do is the following:
float foobar(foo param1, bar param2, float meanValue = mean(param1, param2));
While passing in a function as a default parameter is legal, the compiler (VS2008) complains that param1 and param2 are not declared - because the parameters get pushed onto the stack right-to-left, starting with meanValue. Of course, I can't reverse the order of parameters, since in that case I wouldn't be able to specify a default value for the first parameter.
I could pass in some value like -10000 for the mean to tell myself to call the mean() function; or I could overload every function (and there are 10+ to overload), but that's not very neat. I think it's really cool that you can call a function as a default parameter and I'm wondering if there's a neat way to accomplish what I'm trying to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C++ 标准没有规定参数按什么顺序压入堆栈,或者是否压入它们,或者体系结构上是否有堆栈。
您没有提供太多关于为什么有这么多此类函数以及它们有何不同的信息,但以下内容可能有助于减少重载的数量:
请注意,您可以设置结果类型和调用的函数,以及
mean()
函数,如果需要的话,还有所有模板参数。In which order parameters are pushed to the stack, or whether they are pushed at all, or whether there even is a stack on the architecture, is not specified by the C++ standard.
You don't give much information about why you have so many such functions, and how they differ, but maybe the following would help reduce the number of overloads:
Note that you can make the result type and the function called, and the
mean()
function, all template parameters, too, if you need to.