samedi 23 septembre 2017

Why unscoped enums' declaration compiles?

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);
    f(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.

Aucun commentaire:

Enregistrer un commentaire