Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

enum Foo {
    Bar,
    Baz
};

template<enum Foo = Bar> class Clazz {

};

template<> class Clazz<Baz> {

};

The VC++ compiler reports several errors on the template specialization:

<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. Is this a bug with VC++?

Replacing the 'enum Foo' in the template declaration with just 'int' causes the errors to go away. However, this is not an acceptable answer, as I'm trying to port a large code base over to VC++.

like image 373
Harry Wagstaff Avatar asked Aug 22 '19 14:08

Harry Wagstaff


2 Answers

Your code will compile if you use the Standards Conformance Mode compiler option /permissive- to specify standards-conforming compiler behavior.

You can add that option on the command line or in the "Project property page -> C/C++ -> Language -> Conformance mode".

like image 176
Blastfurnace Avatar answered Nov 17 '22 01:11

Blastfurnace


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.

like image 1
Jeffrey Avatar answered Nov 17 '22 02:11

Jeffrey