I was trying out the constexpr functions and stumbled upon the below example of implementing Fibonacci numbers
There is no logical difference between fibon2 and fibon1 but I still get the compilation error of exceeding template initializations for the fibon1.
What i'm missing here?
#include <cstdint>
#include <iostream>
template <int32_t x>
constexpr int32_t fibon2() {
if constexpr (x == 0)
return 1;
else if constexpr (x == 1)
return 1;
else if constexpr (x == 2)
return 1;
else
return fibon2<x - 1>() + fibon2<x - 2>();
}
template <int32_t x>
constexpr int32_t fibon1() {
if constexpr (x == 0) return 1;
if constexpr (x == 1) return 1;
if constexpr (x == 2) return 1;
return fibon1<x - 1>() + fibon1<x - 2>();
}
int32_t fibon3(int32_t x) {
if (x == 1) return 1;
if (x == 2) return 1;
return fibon3(x - 1) + fibon3(x - 2);
}
int main() {
std::cout << fibon3(2) << std::endl;
std::cout << fibon2<2>() << std::endl;
std::cout << fibon1<2>() << std::endl;
return 0;
}