在像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.
更多推荐
发布评论