Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable template partial specialization and constexpr

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.

like image 237
winterlight Avatar asked Oct 17 '22 19:10

winterlight


1 Answers

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

like image 131
Edgar Rokjān Avatar answered Oct 21 '22 08:10

Edgar Rokjān