嵌套模板类型在Visual Studio编译通过但GCC报错,如何解决?
GCC编译模板代码报错的解决方法
问题代码
template<class T, int Cap> struct stack_collection { }; template<int Cap> struct generate_stack_collection { template<class T> using type = stack_collection<T, Cap>; }; template<template<class> class Col> class collection_user { }; int main() { collection_user<typename generate_stack_collection<5>::type> col; }
这段代码可在Visual Studio/MSVC正常编译,但GCC编译失败,需要补充语法指令让GCC兼容。
GCC报错信息
<source>: In function 'int main()': <source>:23:64: error: invalid use of template-name 'generate_stack_collection<5>::type' without an argument list 23 | collection_user<typename generate_stack_collection<5>::type> col; | ^~~~ <source>:12:15: note: 'template<class T> using type = stack_collection<T, 5>' declared here 12 | using type = stack_collection<T, Cap>; | ^~~~ <source>:23:68: error: template argument 1 is invalid 23 | collection_user<typename generate_stack_collection<5>::type> col; | ^ ASM generation compiler returned: 1 <source>: In function 'int main()': <source>:23:64: error: invalid use of template-name 'generate_stack_collection<5>::type' without an argument list 23 | collection_user<typename generate_stack_collection<5>::type> col; | ^~~~ <source>:12:15: note: 'template<class T> using type = stack_collection<T, 5>' declared here 12 | using type = stack_collection<T, Cap>; | ^~~~ <source>:23:68: error: template argument 1 is invalid 23 | collection_user<typename generate_stack_collection<5>::type> col; | ^ Execution build compiler returned: 1
修复方案
修改main函数中的代码,在type前添加template关键字:
int main() { collection_user<typename generate_stack_collection<5>::template type> col; }
原理说明
- GCC严格遵循C++标准:当访问依赖类型的嵌套模板别名时,必须用
template关键字明确标识这是一个模板,否则编译器会将其误认为普通类型或成员变量。 - MSVC对模板语法的检查相对宽松,能自动推断
type的模板属性,但这是非标准的行为。这里的typename用于指明嵌套名称是类型,而template用于进一步指明该类型本身是模板别名,二者缺一不可。
内容的提问来源于stack exchange,提问作者uhsl_m
相关产品推荐
相关产品推荐

