Can somebody explain to me, why the first call using the template function is falling into an infinite loop, while the second compile-time function runs correctly?
#include <iostream>
using namespace std;
template<int N, int M>
struct commondivs {
static const int val = (N<M) ? commondivs<N,(M-N)>::val : commondivs<(N-M),M>::val;
};
template<int N>
struct commondivs<N,N> {
static const int val = N;
};
int commondiv(int N, int M){
if(N==M){
return N;
}
return (N<M)?commondiv(N,(M-N)):commondiv((N-M),M);
}
int main() {
cout << commondivs<9,6>::val << endl;
cout << commondiv(9,6) << endl;
return 0;
}
constexpr
is not an option. – Mullconstexpr
is not an option. (It was introduced in C++11). That does invalidate existing answers. Exxul, please clarify which C++ version you're limited to. – Wellspring