Reputation: 626
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.
Upvotes: 2
Views: 1513
Reputation: 1192
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.
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.
Upvotes: 5