c++ - 变量模板偏特化和 constexpr

标签 c++ templates c++14

我正在努力理解模板,特别是变量模板。考虑一下:

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 Studio 2015。

最佳答案

我想这是 MSVC 编译器中的一个错误。

根据 thisMSVC 2015 更新 2 以来,页面变量模板应该可用。似乎即使在 更新 3 中它们也无法正常工作。

无论如何,您的代码在 gcc 6.1 下运行良好:wandbox

关于c++ - 变量模板偏特化和 constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41418432/

相关文章:

c++ - 使用 SIMD 的非同质比较

c++ - 有没有为特定模板值添加成员变量的方法?

c++ - 我可以重载采用指针和非构造模板对象的运算符吗?

c++ - 如何检查是否为 C++ 中的模板定义了特定运算符?

c++ - xcb 忽略重复键

c++ - 使用通用引用时的类型推导

c++ - 事件发射器和成员方法自动注册为监听器

c++ - Qt : AddressBook tutorial 中的内存管理

c++ - 使用循环 *AND 交换填充的数组

c# - 如何在 Unity Android 应用程序中使用 OpenCV 中的 ARCore 相机图像?