Skip to content

Instantly share code, notes, and snippets.

View njlr's full-sized avatar
🌏
F# ing

njlr njlr

🌏
F# ing
View GitHub Profile
constexpr unsigned fibonacci(const unsigned x) {
return x <= 1 ?
1 :
fibonacci(x - 1) + fibonacci(x - 2);
}
int main() {
return fibonacci(5);
}
template<unsigned n>
struct Fibonacci {
static const unsigned value = Fibonacci<n - 1>::value + Fibonacci<n - 2>::value;
};
template<>
struct Fibonacci<0> {
static const unsigned value = 0;
};
template<class L, class R>
auto fold(L l, R r) {
using lTag = typename L::tag;
using rTag = typename R::tag;
if constexpr (is_base_of<rTag, BarTag>::value) {
if constexpr (is_same<lTag, FooTag>::value) {
return foldFB(l, r);
} else {
return foldBB(l, r);
}
struct BazTag : FooTag, BarTag {};
template<class L, class R,
enable_if_t<
is_same<L::tag, FooTag>::value &&
is_base_of<R::tag, BarTag>::value
> fold(L l, R r) {
return foldFB(l, r);
}
struct FooTag {};
struct BarTag {};
auto foldFF(...) {}
auto foldFB(...) {}
auto foldBF(...) {}
auto foldBB(...) {}
struct A {
/* ... */
template<class T>
int compute(T x) {
if constexpr( supportsAPI(T{}) ) {
// only gets compiled if the condition is true
return x.Method();
} else {
return 0;
}
}
template<class T>
auto compute(T x) -> decltype( enable_if_t< supportsAPI(T{}), int>{}) {
return x.Method();
}
template<class T>
auto compute(T x) -> decltype( enable_if_t<!supportsAPI(T{}), int>{}) {
return 0;
}
template<class T>
constexpr auto supportsAPI(T x) -> decltype(x.Method1(), x.Method2(), true_type{}) {
return {};
}
constexpr auto supportsAPI(...) -> false_type {
return {};
}
template<unsigned n>
struct Get {
template<class X, class…Xs>
constexpr auto operator()(X x, Xs…xs) {
if constexpr(n > sizeof…(xs) ) {
return;
} else if constexpr(n > 0) {
return Get<n-1>{}(xs…);
} else {
return x;
template<unsigned n>
struct Arg {
template<class X, class...Xs>
constexpr auto operator()(X x, Xs...xs) {
return Arg<n - 1>{}(xs...);
}
};
template<>
struct Arg<0> {