Advertisement
Guest User

Untitled

a guest
Jan 27th, 2015
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. // Calculate the value passed as T
  2. template <int T>
  3. struct Fibonacci
  4. {
  5.     enum { value = (Fibonacci<T - 1>::value + Fibonacci<T - 2>::value) };
  6. };
  7.  
  8. // In the template meta-programming, we do not have conditionals, so instead
  9. // we use struct-overloading like mechanism to set constraints, we do this for
  10. // numbers 0, 1 and 2, just like our algorithm in the function above.
  11. template <>
  12. struct Fibonacci<0>
  13. {
  14.     enum { value = 1 };
  15. };
  16.  
  17. template <>
  18. struct Fibonacci<1>
  19. {
  20.     enum { value = 1 };
  21. };
  22.  
  23. template <>
  24. struct Fibonacci<2>
  25. {
  26.     enum { value = 1 };
  27. };
  28.  
  29. // in the end, we get the value
  30. int main()
  31. {
  32.     int x = Fibonacci<45>::value;
  33.     cout << x << endl;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement