Jason Doege Jason Doege - 19 days ago 4x
C++ Question

Is there any way to perform function signature matching based on parameter values?

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?


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.