I am trying to understand templates, and variable templates specifically. Consider this:
template<int M, int N>
const int gcd1 = gcd1<N, M % N>;
template<int M>
const int gcd1<M, 0> = M;
std::cout << gcd1<9, 6> << "\n";
It prints 0
which is wrong. However, if I use constexpr
instead of const
above, I get the proper answer 3
. I again get proper answer with structure template:
template<int M, int N>
struct gcd2 {
static const int value = gcd2<N, M % N>::value;
};
template<int M>
struct gcd2<M, 0> {
static const int value = M;
};
std::cout << gcd2<9, 6>::value << "\n";
What am I doing wrong?
Edit:
gcd1
compiles fine without the base-case specialization also. How come? I am using Visual Studio 2015.
I suppose that it is a bug in MSVC compiler.
According to this page variable templates should be available since MSVC 2015 update 2. Seems that they do not work correctly even in update 3.
Anyway your code works fine with gcc 6.1: wandbox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With