5

我正在尝试实现一个模板化的 C 数组,其专业化如下:

// template definition
template< int a, int b > constexpr int    arr[]       = { 1 };

// partial specialization, works ok
template< int b >        constexpr double arr<0, b>[] = { 2.0 };

// full specialization, compile error in MSVC, ok in g++
template< >              constexpr float  arr<1, 0>[] = { 3.0f };

我将 MSVC 编译器与 Visual Studio 2017 一起使用,C++ 标准设置为 C++17,编译器抱怨说C2133: 'arr<1,0>': unknown size,因此将大小添加1到完全专业化可以解决错误。-pedantic但是,它在带有标志的Ubuntu g++ 8.1.0 下编译。

在我看来,函数和类的完全特化就像定义了一个非模板版本,所以我想这也应该适用于变量模板,上面的完全特化可以等同于(除了名称)

constexpr float arr_with_a1_and_b0[] = { 3.0f };

这对我来说看起来很有效,因为大小应该从列表初始化(聚合初始化)中推导出来。

我的问题是:上面的代码是有效的 C++ 吗?哪个编译器是正确的?

4

1 回答 1

2

这是由于 MSVC 编译器的错误:https ://developercommunity.visualstudio.com/t/compiler-error-c2133-unknown-size-for-constant-tem/228098 。从带有 Visual Studio 16.10.1 的 MSVC 开始,此问题已得到修复。

于 2021-10-26T21:24:35.157 回答