You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

模板参数包在GCC中可用但MSVC报错,哪个编译器合规?

模板参数包与数组形参的编译器合规性确认

你的代码符合C++标准,GCC和Clang的行为正确,MSVC的报错属于实现缺陷。

代码示例

#include<cstddef>

template <typename T, std::size_t...Indices>
void func(T (&)[sizeof...(Indices)]);
int main()
{
    int arr[4];
    func<int, 1,2,3,4>(arr);  //msvc rejects but clang and gcc accepts
}

MSVC报错信息

source>(11): error C2182: 'func': this use of 'void' is not valid
<source>(11): error C2988: unrecognizable template declaration/definition
<source>(11): error C2059: syntax error: ')'
<source>(13): error C2143: syntax error: missing ';' before '{'
<source>(13): error C2447: '{': missing function header (old-style formal list?)

合规性解释

C++标准允许在函数模板的形参中使用依赖于模板参数的常量表达式指定数组大小。这里sizeof...(Indices)是依赖于模板参数包Indices的常量表达式,当显式指定Indices为1,2,3,4时,sizeof...(Indices)的值为4,与实参arr[4]的大小完全匹配,模板实例化逻辑合法。MSVC未能正确解析这种依赖于参数包大小的数组形参声明,属于编译器实现错误。

内容的提问来源于stack exchange,提问作者user20562802

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:15:56