函数调用作为默认参数 - 可以在封装中使用其他参数吗?

发布于 2024-12-24 21:07:18 字数 613 浏览 1 评论 0原文

假设我有以下函数,代码中的许多其他函数都需要它生成的值:

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) 抱怨 param1param2 未声明 - 因为参数从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

三人与歌 2024-12-31 21:07:18

C++ 标准没有规定参数按什么顺序压入堆栈,或者是否压入它们,或者体系结构上是否有堆栈。

您没有提供太多关于为什么有这么多此类函数以及它们有何不同的信息,但以下内容可能有助于减少重载的数量:

template< typename T1, typename T2 >
float foobar(T1 param1, T2 param2)
{
    return foobar(param1, param2, mean(param1, param2));
}

请注意,您可以设置结果类型和调用的函数,以及 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:

template< typename T1, typename T2 >
float foobar(T1 param1, T2 param2)
{
    return foobar(param1, param2, mean(param1, param2));
}

Note that you can make the result type and the function called, and the mean() function, all template parameters, too, if you need to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文