Skip to content

Instantly share code, notes, and snippets.

@loliGothicK
Last active April 27, 2018 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loliGothicK/4377c461d682f52067e2d728401568e1 to your computer and use it in GitHub Desktop.
Save loliGothicK/4377c461d682f52067e2d728401568e1 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <functional>
template <class F>
struct Fixed {
F f;
Fixed(F f): f{f} {}
template <class... Args>
decltype(auto) operator()(Args&&... args) const {
return f(std::ref(*this), std::forward<Args>(args)...);
}
};
// for C++14
template <class F>
Fixed<std::decay_t<F>>
fix(F&& f) { return {std::forward<F>(f)}; }
int
main(){
// C++14: use fix function template
auto fib14 = fix([](auto f, int n) -> int {
switch ( n ) {
case 0: return 0;
case 1: return 1;
default: return f( n - 2 ) + f( n - 1 );
}
});
std::cout << fib14(7) << std::endl;
// C++17: class template deduction
Fixed fib17 = [](auto f, int n) -> int {
switch ( n ) {
case 0: return 0;
case 1: return 1;
default: return f( n - 2 ) + f( n - 1 );
}
};
std::cout << fib17(7) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment