Skip to content

Instantly share code, notes, and snippets.

@kinchungwong
Created November 29, 2013 00:51
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 kinchungwong/7700105 to your computer and use it in GitHub Desktop.
Save kinchungwong/7700105 to your computer and use it in GitHub Desktop.
C++ TMP - Non-working skeleton for Fibonacci that contains lazy evaluation using integral constant types.
#include <iostream>
using namespace std;
template <class CValueOne, class CValueTwo> struct Sum;
template <int N1, int N2>
struct Sum<std::integral_constant<int, N1>, std::integral_constant<int, N2>>
{
typedef std::integral_constant<int, N1+N2> type;
};
template <class CValueOne, class CValueTwo> struct Equals;
template <int N1, int N2>
struct Equals<std::integral_constant<int, N1>, std::integral_constant<int, N2>>
: std::false_type
{};
template <int N1>
struct Equals<std::integral_constant<int, N1>, std::integral_constant<int, N1>>
: std::true_type
{};
template <bool Cond, class EvalIfTrue, class EvalIfFalse>
struct ConditionalEval;
template <class EvalIfTrue, class EvalIfFalse>
struct ConditionalEval<false, EvalIfTrue, EvalIfFalse>
{
typedef typename EvalIfFalse::type type;
};
template <class EvalIfTrue, class EvalIfFalse>
struct ConditionalEval<true, EvalIfTrue, EvalIfFalse>
{
typedef typename EvalIfTrue::type type;
};
template <class CIndex>
struct Fibonacci
{
struct details
{
typedef std::integral_constant<int, 0> N0;
typedef std::integral_constant<int, 1> N1;
typedef std::integral_constant<int, 2> N2;
typedef std::integral_constant<int, 42> Nuniverse;
};
typedef typename ConditionalEval<
Equals<CIndex, typename details::N0>::value,
typename details::N1,
typename ConditionalEval<
Equals<CIndex, typename details::N1>::value,
typename details::N1,
typename details::Nuniverse
>::type
>::type type;
};
int main()
{
typedef std::integral_constant<int, 0> N0;
typedef std::integral_constant<int, 1> N1;
typedef std::integral_constant<int, 2> N2;
typedef std::integral_constant<int, 3> N3;
typedef std::integral_constant<int, 4> N4;
std::cout << Fibonacci<N2>::type::value << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment