Skip to content

Instantly share code, notes, and snippets.

@unixnut
Last active April 5, 2025 17:09
Show Gist options
  • Select an option

  • Save unixnut/7cf83dfc2080bb4bd3520dd164785ee7 to your computer and use it in GitHub Desktop.

Select an option

Save unixnut/7cf83dfc2080bb4bd3520dd164785ee7 to your computer and use it in GitHub Desktop.
C++ Weekly - Ep 13 Fibonacci: You're Doing It Wrong
#include <iostream>
#include <array>
#include <utility>
#include <sstream>
template<int I>
struct Fib
{
static const int val Fib<I-1>::val + Fib<I-2>::val;
};
template<>
struct Fib<0>
{
static const int val = 0;
};
template<>
struct Fib<1>
{
static const int val = 1;
};
template<size_t ... I>
const int fib_impl(std::index_sequence<I...>, const int i)
{
constexpr std::array<int, sizeof...(I)> a
= {Fib<I>::val...};
return a[i];
}
const int fib(const int i)
{
return fib_impl(std::make_index_sequence<47>(), i);
}
int main(int argc, const char *argv[])
{
// Fixed value only
//# std::cout << Fib<46>::val << '\n';
if (argc == 2)
{
std::stringstream ss(argv[1]);
int i;
ss >> i;
std::cout << fib(i) << '\n';
}
else
{
std::cerr << "fib-template: Invalid number of command line arguments" << '\n';
return 1;
}
// Added to avoid warning
return 0;
}
@unixnut

unixnut commented Apr 5, 2025

Copy link
Copy Markdown
Author

This example, written by Jason Turner and corrected by me, computes the Fibonacci sequence up to the limit associated with a long int, at compile time and puts it into an array that's indexable AT RUN TIME.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment