为什么 Visual Studio C++ 编译器拒绝将枚举作为模板参数?
Why is the Visual Studio C++ Compiler rejecting an enum as a template parameter?
我正在使用 Microsoft Visual Studio 2019 编译器 (cl.exe),它拒绝了 Clang 和 GCC 都接受的一些代码,这些代码与使用枚举作为模板参数有关,其中模板专用于特定的枚举值。
enum Foo {
Bar,
Baz
};
template<enum Foo = Bar> class Clazz {
};
template<> class Clazz<Baz> {
};
VC++ 编译器报告了几个关于模板特化的错误:
<source>(10): error C2440: 'specialization': cannot convert from 'Foo' to 'Foo'
<source>(10): note: Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast)
此代码被 Clang 和 GCC 无误地接受。这是 VC++ 的错误吗?
将模板声明中的 'enum Foo' 替换为 'int' 会导致错误消失。但是,这不是一个可接受的答案,因为我正在尝试将大型代码库移植到 VC++。
你少了一个T:
template<enum Foo T = Bar> class Clazz {
或者有一个额外的枚举:
template<Foo = Bar> class Clazz {
第二个更好,谢谢 François。
如果您使用 Standards Conformance Mode 编译器选项 /permissive-
指定符合标准的编译器行为,您的代码将编译。
您可以在命令行或 "Project property page -> C/C++ -> Language -> Conformance mode" 中添加该选项。
我正在使用 Microsoft Visual Studio 2019 编译器 (cl.exe),它拒绝了 Clang 和 GCC 都接受的一些代码,这些代码与使用枚举作为模板参数有关,其中模板专用于特定的枚举值。
enum Foo {
Bar,
Baz
};
template<enum Foo = Bar> class Clazz {
};
template<> class Clazz<Baz> {
};
VC++ 编译器报告了几个关于模板特化的错误:
<source>(10): error C2440: 'specialization': cannot convert from 'Foo' to 'Foo'
<source>(10): note: Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast)
此代码被 Clang 和 GCC 无误地接受。这是 VC++ 的错误吗?
将模板声明中的 'enum Foo' 替换为 'int' 会导致错误消失。但是,这不是一个可接受的答案,因为我正在尝试将大型代码库移植到 VC++。
你少了一个T:
template<enum Foo T = Bar> class Clazz {
或者有一个额外的枚举:
template<Foo = Bar> class Clazz {
第二个更好,谢谢 François。
如果您使用 Standards Conformance Mode 编译器选项 /permissive-
指定符合标准的编译器行为,您的代码将编译。
您可以在命令行或 "Project property page -> C/C++ -> Language -> Conformance mode" 中添加该选项。