可变模板部分专业化和constexpr

variable template partial specialization and constexpr

本文关键字:专业化 constexpr 板部      更新时间:2023-10-16

我试图理解模板和变量模板。考虑一下:

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";

它打印了 0,这是错误的。但是,如果我使用上面的constexpr代替const,则获得了正确的答案3。我再次使用结构模板得到正确的答案:

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";

我在做什么错?

编辑: gcd1也没有基本案例专业化。怎么会?我正在使用Visual Studio2015。

我想这是 msvc 编译器中的错误。

根据此页面,由于 MSVC 2015 Update 2 ,应可用变量模板。似乎它们即使在更新3 中也无法正常工作。

无论如何,您的代码与 gcc 6.1 :wandbox

正常工作