我想通過Y-combinator在C++中引用函數名稱來編寫遞歸。不過,我想不通的功能的類型如下嘗試:是否有可能在C++中使用可自行調用的實際函數類型?
#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;
}
編譯器不能推斷出是什麼Function
,也不可以我。然後我嘗試以下:
#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;
}
此,相比於上述的例子的情況下,不同的是我改變功函數以一個可調用的對象,該對象Function
被容易地推斷爲Factorial
,導致下面的完整實現的該組合子:
#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;
}
的問題是,是否有可能在結構Factorial
改寫到一個普通的功能?
看看你的第一個例子:你爲什麼不想引用函數名?爲什麼'factorial1'是一個模板?如果不是「factorial1」,那麼「自我」會是什麼? –
Y組合器需要一個更強大的類型系統(模板提供,如你自己發現的,也顯示在[這裏在Rosetta代碼](https://rosettacode.org/wiki/Y_combinator#C.2B.2B))或者它需要(無類型)lambda演算中的_nonexistent_type系統。所以嘗試使用'std :: uintptr_t'並在需要的地方進行投射......(順便說一下:對此評論沒有保證。) – davidbak
人們用y combinator回答了我無關的問題:http://stackoverflow.com/questions/42796710/call -c-recursive-lambda-in-the-line-where-it-is-declaration- – NoSenseEtAl