Created
May 26, 2019 21:27
Star
You must be signed in to star a gist
Cool stuff todo with C++
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
#include <cstdio> | |
#include <string> | |
#include <type_traits> | |
namespace | |
{ | |
template<int i> | |
struct fac | |
{ | |
static constexpr int value = i*fac<i-1>::value; | |
}; | |
template<> | |
struct fac<0> | |
{ | |
static constexpr int value = 1; | |
}; | |
auto add = [](auto x, auto y) { return x + y; }; | |
template<typename ...T> | |
struct my_tuple; | |
template<typename THead, typename ...TRest> | |
struct my_tuple<THead, TRest...> : my_tuple<TRest...> | |
{ | |
using this_t = my_tuple<THead, TRest...>; | |
using head_t = std::decay_t<THead> ; | |
using rest_t = my_tuple<TRest...> ; | |
head_t head; | |
template<int i> | |
struct getter | |
{ | |
this_t const & t; | |
getter (this_t const & t) | |
: t (t) | |
{ | |
} | |
auto operator()() const | |
{ | |
return rest_t::getter<i - 1>(t)(); | |
} | |
}; | |
template<> | |
struct getter<0> | |
{ | |
this_t const & t; | |
getter (this_t const & t) | |
: t (t) | |
{ | |
} | |
auto operator()() const | |
{ | |
return t.head; | |
} | |
}; | |
my_tuple(head_t h, TRest... rest) | |
: rest_t (rest...) | |
, head (std::move (h)) | |
{ | |
} | |
template<int i> | |
auto get() const | |
{ | |
return getter<i>(*this)(); | |
} | |
}; | |
template<> | |
struct my_tuple<> | |
{ | |
}; | |
} | |
int main() | |
{ | |
// computed compile-time, you can do it with contexpr but how fun is that? | |
auto f = fac<5>::value; | |
printf("fac: %d\n", f); | |
// add is a parametric polymorphic function object, that is pretty cool | |
printf("add: %d\n", add(1,2)); | |
printf("add: %f\n", add(1,2.14)); | |
printf("add: %s\n", add(std::string("3"), ".14").c_str()); | |
// Roll your own tuple implementation using variadic templates | |
my_tuple<int, double> t(1, 3.14); | |
auto t0 = t.get<0>(); | |
auto t1 = t.get<1>(); | |
printf("tuple: %d, %f\n", t0, t1); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment