Why unscoped enums' declaration compiles?

安稳与你 提交于 2020-07-19 06:45:30

问题


In the Effective Modern C++ book of Scott Meyers it is mentioned that one of the main difference between unscoped and scoped enums(enum class) is that we can't forward declare the former (see Chapter 3, Item 10 - "Prefer scoped enums to unscoped enums"). For example:

enum Color;            *// error!*
enum class Color;      *// fine*

But I've written below mentioned small example and saw that it is not so.

test.h

#pragma once
enum names;
void print(names n);

test.cpp

#include "test.h"

#include <iostream>

enum names { John, Bob, David };

void print(names n)
{
    switch (n)
    {
    case John:
    case Bob:
    case David:
        std::cout << "First names." << std::endl;
        break;
    default:
        std::cout << "Other things" << std::endl;
    };
}

main.cpp

#include "test.h"
#include <iostream>

int main()
{
    names n = static_cast<names>(2);
    print(n);
    return 0;
}

I've used VC14 compiler (Visual Studio 2015). Is this bug or feature of the compiler? Something else? If this is bug or feature (considering that Meyers says that this is the major difference between unscoped and scoped enums) it means that compilers are capable of managing the situation where we can declare unscoped enums. Hence, was there a need to add a new keyword class after enum? Of course, someone will say that there are other two features of scoped enums. As I got it, above mentioned feature is the most important.


回答1:


C++11

First: C++11 does allow forward declaration of unscoped enums. You just have to give the underlying type to the compiler (example from Effective Modern C++, Chapter 3, Item 10):

enum Color: std::uint8_t;

What you use is a non-standard extension of the compiler, but its possible anyway.

important or not

Scott Meyers says in the quoted chapter:

It may seem that scoped enums have a third advantage over unscoped enums, because scoped enums may be forward-declared, i.e., their names may be declared without specifying their enumerators: [...] In C++11, unscoped enums may also be forward-declared, but only after a bit of additional work.

"May seem" means the opposite of "is". Scott Meyers himself states that this is not an important feature in said book.



来源:https://stackoverflow.com/questions/46379572/why-unscoped-enums-declaration-compiles

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!