Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a real function type in C++ which is callable with itself?

Tags:

I am trying to write recursion without referencing the function name in C++ by means of Y-combinator. However, I can't figure out the type of the Function in the following attempt:

#include <iostream>

using std::cin;
using std::cout;

template<class Function> unsigned long factorial1(Function self, unsigned long n) {
    return n ? n * self(self, n - 1) : 1;
}

unsigned long factorial(unsigned long n) {
    return factorial1(factorial1, n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}

The compiler cannot deduce what is Function, neither can me. Then I tried the following:

#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

unsigned long factorial(unsigned long n) {
    return Factorial()(Factorial(), n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}

This, when compared to the above example, the difference is I changed the work function to a callable object, which Function is deduced easily as Factorial, leading to the following complete implementation of the combinator:

#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

template<class Function> auto y(Function f) {
    return [f](auto n) {
        return f(f, n);
    };
}

int main() {
    unsigned long n;
    cin >> n;
    cout << y(Factorial())(n) << '\n';
    return 0;
}

The question is that, is it possible to rewrite the struct Factorial to a plain function?