有没有办法根据参数值执行功能签名匹配?(Is there any way to perform function signature matching based on parameter value

编程入门 行业动态 更新时间:2024-10-13 20:15:36
没有办法根据参数值执行功能签名匹配?(Is there any way to perform function signature matching based on parameter values?)

在像Haskell这样的面向函数的语言中,可以将函数定义重载为参数签名的几个轴。 C ++支持参数的数量和类型。 其他语言支持参数值甚至保护子句(测试条件参数的代码。)例如Haskell中的阶乘实现:

factorial :: (Integral a) => a -> a factorial 0 = 1 factorial n = n * factorial (n - 1)

当参数为0时,factorial的定义与参数为任何其他整数时的factorial定义不同。

我没有在C ++中找到这种功能,并且首先想到用语言实现它很难。 进一步的反思让我觉得它实际上相当容易,并且是语言的一个很好的补充,所以我必须错过它。

有没有办法在本机语法或模板中执行此操作?

In functional oriented languages like Haskell, one can overload function definitions an several axis of parameter signature. C++ supports number and type of arguments. Other languages support argument values and even guard clauses (code that tests the arguments for conditions.) For instance the factorial implementation in Haskell:

factorial :: (Integral a) => a -> a factorial 0 = 1 factorial n = n * factorial (n - 1)

Where the definition for factorial when the argument is 0 differs from the definition for factorial when the argument is any other integer.

I have not found this capability in C++ and thought, at first, that it would be difficult to implement in the language. Further reflection made me think it actually would be fairly easy and a nice addition to the language, so I must be missing it.

Is there any way to do this either in native syntax or templates?

最满意答案

我认为这里真正的答案是没有确切的等价物。 然而。 模板专业化很接近,但只能在编译时工作,有些限制了它的可用性。 我们当然有分支,但与其他函数式编程语言中的模式匹配相比,功能有限。

目前有一个关于C ++中模式匹配的提议: P0095r1 ,它允许以下阶乘定义,假设概念:

template <Integral I> I factorial(I n) { return inspect(n) { 0 => 1 n => n * factorial(n-1) }; }

我不完全确定语法,但话说回来,它只是一个提案到目前为止,所以语法本身可能会改变。

I think the real answer here is that there isn't an exact equivalent. Yet. Template specialization is close, but that only works at compile time, which several limits its usability. We have branching of course, but that has limited power compared to what pattern matching can do in other functional programming languages.

There is a proposal currently for pattern matching in C++: P0095r1 which would allow the following definition of factorial, assuming concepts:

template <Integral I> I factorial(I n) { return inspect(n) { 0 => 1 n => n * factorial(n-1) }; }

I'm not totally sure on the syntax, but then again, it's just a proposal so far, so the syntax itself could change.

更多推荐

本文发布于:2023-08-01 21:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1365836.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有办法   参数   功能   perform   function

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!