简体   繁体   English

为什么Visual Studio C ++编译器拒绝将枚举作为模板参数?

[英]Why is the Visual Studio C++ Compiler rejecting an enum as a template parameter?

I'm using the Microsoft Visual Studio 2019 compiler (cl.exe), and it is rejecting some code accepted by both Clang and GCC, related to using enums as template parameters, where the templates are specialized for particular enum values. 我正在使用Microsoft Visual Studio 2019编译器(cl.exe),它拒绝了Clang和GCC接受的一些代码,这些代码与将枚举用作模板参数有关,其中模板专门用于特定的枚举值。

enum Foo {
    Bar,
    Baz
};

template<enum Foo = Bar> class Clazz {

};

template<> class Clazz<Baz> {

};

The VC++ compiler reports several errors on the template specialization: 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)

This code is accepted without errors by both Clang and GCC. Clang和GCC均接受此代码,没有错误。 Is this a bug with VC++? 这是VC ++的错误吗?

Replacing the 'enum Foo' in the template declaration with just 'int' causes the errors to go away. 用“ int”代替模板声明中的“ enum Foo”会导致错误消失。 However, this is not an acceptable answer, as I'm trying to port a large code base over to VC++. 但是,这不是可接受的答案,因为我正在尝试将大型代码库移植到VC ++。

Your code will compile if you use the Standards Conformance Mode compiler option /permissive- to specify standards-conforming compiler behavior. 如果您使用标准符合性模式编译器选项/permissive-来指定符合标准的编译器行为,则将编译您的代码。

You can add that option on the command line or in the "Project property page -> C/C++ -> Language -> Conformance mode". 您可以在命令行或“项目属性页-> C / C ++->语言->一致性模式”中添加该选项。

You are missing a T: 您缺少电话:

template<enum Foo T = Bar> class Clazz {

Or have an extra enum: 或者有一个额外的枚举:

template<Foo = Bar> class Clazz {

This second one is much nicer, thanks François. 感谢François,第二个要好得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM