Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize enum c++

Tags:

c++

enums

I create an enum called Types:

enum  Types {Int,Double,String};  

When I create an object and initialize it with one of the enum allowed values I get the following error: "Error: type name is not allowed".

Types ty = Types.Double;  

Any ideas?

like image 381
user3165438 Avatar asked Sep 14 '14 08:09

user3165438


2 Answers

In C++, there are two different types of enumerations - scoped and unscoped ones (the former was introduced with C++11). For unscoped ones the names of the enumerators are directly introduced into the enclosing scope.

N3337 §7.2/10

Each enum-name and each unscoped enumerator is declared in the scope that immediately contains the enum-specifier. Each scoped enumerator is declared in the scope of the enumeration. These names obey the scope rules defined for all names in (3.3) and (3.4).

Your enumeration is unscoped, therefore it suffices to write

Types ty = Double;

For scoped enumerations, as the name suggests, the enumerators are declared in the enumeration scope and have to be qualified with the enumeration-name:

enum class ScopedTypes {Int,Double,String}; 
enum UnscopedTypes     {Int,Double,String}; 

ScopedTypes a = ScopedTypes::Double;
//ScopedTypes b = Double; // error

UnscopedTypes c = UnscopedTypes::Double;
UnscopedTypes d = Double;
like image 112
Columbo Avatar answered Oct 14 '22 19:10

Columbo


Either use

Types ty = Double;  

or

enum  class Types {Int,Double,String};  
Types ty = Types::Double;  
like image 20
Vlad from Moscow Avatar answered Oct 14 '22 21:10

Vlad from Moscow