简体   繁体   中英

Scoped enumerations: error: cannot convert ‘int’ to ‘Handle’ in initialization

I am reading the Scoped enumerations page from here :

在此输入图像描述 So I decided to give it a try:

$ cat e.cxx 
#include <cstdint>
enum class Handle : uint32_t { Invalid = 0 };
int main()
{
  Handle h { 42 }; // OK
  return 0;
}
$ g++ -std=c++11 e.cxx
e.cxx: In function ‘int main()’:
e.cxx:5:17: error: cannot convert ‘int’ to ‘Handle’ in initialization
   Handle h { 42 }; // OK

             ^

Using:

$ g++ --version
g++ (Debian 5.3.1-14) 5.3.1 20160409
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

If I now check the C++11 support in GCC, it appears as if everything is supported since GCC 4.8 .

So which page am I reading it wrong ? The example for Score enumertions is not 100% correct, or the support for C++11 in GCC is still incomplete ?

enum class (or enum struct ) creates a strong type. It can not naively be initialized using the underlying integer type, it needs to be explicitly casted, at least in C++11 and C++14.

The reference screenshot you show is from the upcoming C++17 standard, which relaxes the the requirements a little, and allows that type of initialization.

The wording in question comes from P0138R2 : Construction Rules for enum class Values. As you can see, the paper is dated March 2016 - quite a few years too late for C++11!

The wording is included in the latest working draft N4582 in [dcl.init.list] as suggested:

Otherwise, if T is an enumeration with a fixed underlying type (7.2), [...]

clang 3.9 apparently has already implemented this example, but I wouldn't be surprised that such new features aren't supported by compilers yet. Give it a while.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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