C++ functional programming code snippets

Viewed 1858

I have been working on a project called: Functional Programming Features of C++11/14 (for one of my subjects at university). There are several existing sources and similar presentations about such topics and I found one not so long ago which contained several code snippets that I haven't managed to understand completely (and somehow they can be connected to functional programming). Snippets A and B belonged to recursion and C belonged to lazy evaluation. I'd like to share them with you below:

Snippet A:

#include <iostream>

template <int N>
struct Factorial {
    static int const val = N * Factorial<N - 1>::val;
};

template <>
struct Factorial <0> {
    static int const val = 1;
};

int main() {
    int factorial_of_6 = Factorial<6>::val;
    std::cout << factorial_of_6 << std::endl;
    return 0;
}

Was the point here compile time evaluation (in order to avoid runtime computations and improve performance)? Or are there other advantages, too?

Snippet B:

#include <iostream>

template <int ...>
struct my_sum;

template <>
struct my_sum <> {
    static const int value {0};
};

template <int i, int ... tail>
struct my_sum <i, tail ...> {
    static const int value = i + my_sum<tail ...>::value;
};

int main() {
    int sum {my_sum<1, 2, 3, 4, 5>::value};
    std::cout << sum << std::endl;
    return 0;
}

Same question applies as above.

And here is another snippet which is maybe similar:

Snippet C:

#include <iostream>

template <typename... Args>
void some_function (Args ...) {
    std::cout << sizeof...(Args) << std::endl;
}

int main() {
    some_function ("Every little thing gonna be alright...", 1.0 / 0.0);
    return 0;
}

"The presentation said: C++ is eager but the following will work." Is its point that until I don't care about the given expressions I can tell the quantity of them?

Please, be as specific and detailed as possible, and thank you very much for your patience and help in advance. :)

1 Answers
Related