// clang++ 3.5
// maybe gcc 4.9 support it, but I don't test it
#include<iostream>
int main()
{
auto fac = [&](auto&& self, int x)->int{
return x < 1 ? 1 : x * self(self, x - 1);
};
std::cout<<fac(fac, 3)<<std::endl; //6
return 0;
}
作者:蓝色
链接:https://www.zhihu.com/question/27441424/answer/36643770
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
// clang++ 3.5
// maybe gcc 4.9 support it, but I don't test it
#include<iostream>
template<typename Functor>
struct wrapper_type
{
Functor functor;
template<typename... Args>
decltype(auto) operator()(Args&&... args) const&
{
return functor(functor, std::forward<Args>(args)...);
}
};
template<typename Functor>
wrapper_type<typename std::decay<Functor>::type> wrapper(Functor&& functor)
{
return{ std::forward<Functor>(functor) };
}
int main()
{
auto fac = wrapper([&](auto&& self, int x)->int{
return x < 1 ? 1 : x * self(self, x - 1);
});
std::cout << fac(3) << std::endl; //6
return 0;
}
作者:蓝色
链接:https://www.zhihu.com/question/27441424/answer/36643770
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
#include <iostream>
#include <typeinfo>
#include <functional>
using namespace std;
int main(void)
{
std::function<int(int)> product;
product = [&product](int n) -> int{ return n <= 1? 1 : n * product(n - 1); };
cout << "The answer is: " << product(5) << endl;
}
链接:https://blog.csdn.net/zenny_chen/article/details/6045596