模板参数包在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
相关产品推荐
相关产品推荐

