Last active
August 18, 2016 16:11
-
-
Save nikhedonia/117c5030027be4c950f5645030f1f2dd to your computer and use it in GitHub Desktop.
Gist created by https://fiddle.jyt.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SFINAE - Substitution-Failure-Is-Not-An-Error | |
template<bool condition, class T> | |
struct enable_if { | |
using type = T; | |
}; | |
template<class T> | |
struct enable_if<false,T> | |
{}; | |
template<bool condition, class T> | |
using enable_if_t = typename | |
enable_if<condition,T>::type; | |
// if condition==false then type does not exist | |
// however if we access it during overload resolution, this is not an error | |
template<class T, class U> | |
struct is_same { | |
constexpr static bool value = false; | |
}; | |
template<class T> | |
struct is_same<T,T> { | |
constexpr static bool value = true; | |
}; | |
template<class T> | |
auto incrementIfInt(T x) -> | |
enable_if_t<is_same<int,T>::value,T> { | |
return x+1; | |
} | |
template<class T> | |
auto incrementIfInt(T x) -> | |
enable_if_t<!is_same<int,T>::value,T> { | |
return x; | |
} | |
// lets make some monadic tuples | |
auto apply = [](auto...x) { | |
return [=](auto f) { | |
return f(x...); | |
}; | |
}; | |
// thats how we define operations on each element | |
auto map = [](auto f) { | |
return [=](auto...x) { | |
return apply(f(x)...); | |
}; | |
}; | |
#include<iostream> | |
//test run | |
auto tup = apply(1, 2, 3, "foo", 4.2, "bar"); | |
auto incAndPrint = [](auto x) { | |
auto y = incrementIfInt(x); | |
std::cout << y << std::endl; | |
return y; | |
}; | |
auto tup2 = tup(map(incAndPrint)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment