C++ 2011: Strongly-typed Enums
Enumerations are an important feature of C++, but unlike in other languages, enumerations are not type-safe. There are several problems with the enums: they export their enumerators (the members of an enumeration) to the surrounding scope, you cannot specify the underlying type and the enumerators implicitly convert to int. These problems have been addressed in the new standard with the introduction of "enum class", which are basically strongly-typed enumerations.
Problems with traditional enums
The Scope
Enumerations export their enumerators to the surrounding scope. This has two drawbacks. First, it can lead to name clashes, if two enumerators in different enums declared in the same scope have the same name; second, it's not possible to use an enumerator with a fully qualified name, including the enum name. Let's take for instance the following enum:
enum Selection
{
None,
Single,
Multiple
};
Selection sel = Selection::Single;
The above line would generate an error with GCC ('Selection' is not a class or namespace) and a warning with VC++ (nonstandard extension used: enum 'Selection' used in qualified name). To make it work you have to drop the qualification:
Selection sel = Single;
The second problem appears if we define a new enumeration in the same scope, having an enumerator with the same name as one from Selection.
enum Border
{
None,
Flat,
Raised,
Sunken
};
Both enums have an enumerator called None; since they are exported in the surrounding scope, there is a name clash. To fix it we can either change the name of an enumerator, or put the enums in different namespaces.
namespace Selection
{
enum Selection
{
None,
Single,
Multiple
};
}
namespace Border
{
enum Border
{
None,
Flat,
Raised,
Sunken
};
}
In this case we can write:
Selection::Selection sel = Selection::Single;
Of course, one can argue that using the same name for the namespace and the enum is not a good practice, but this is just an exercise, so you are free to name them however you want.
The Underlying Type
It is not possible to specify the underlying type. It is implementation specific, but it has to be an integral type; it should not be larger than int unless the enumerator value cannot fit an int or unsigned int. Let's take for example the following definition:
namespace Selection
{
enum Selection
{
None = 0,
Single = 1,
Multiple = 0xFFFF0000U
};
}
cout << Selection::Multiple << endl;
The output is different with different compilers. Compiled with VC++ the program outputs -65536, while compiled with GCC the output is 4294901760. The difference is that VC++ always uses int for the underlying type, while GCC is more adaptive.
Now, some compilers do allow you to specify the underlying type. For instance VC++ allows this since version 2005. MSDN says the definition of an enum has the form:
enum [tag] [: type] {enum-list} [declarator];
And you can actually say:
namespace Selection
{
enum Selection : unsigned int
{
None = 0,
Single = 1,
Multiple = 0xFFFF0000U
};
}
In which case, printing Multiple will also show 4294901760.
GCC also allows you to specify an underlying type, however, this is actually supported in the standard only in the new C++ 2011 version.The underlying type leads to another problem: forward declaration is not possible.
enum Selection;
void make_selection(Selection s)
{
}
enum Selection
{
None,
Single,
Multiple
};
The reason is that given only the forward declaration, the compiler does not know the underlying size and thus the size of the enumerator. As a result it cannot compile this piece of code. However, if you try to build this in VC++ you'll notice that it actually compiles. The reason is VC++ always uses int (unless specified otherwise) for the underlying type (as indicated earlier) so it does know the size of the enumerator.
Conversion to int
The values of enumerators implicitly convert to int.
int s1 = None;
The problem arises when you try to do something like this:
enum Selection
{
None = 0,
Single = 1,
Multiple = 2,
};
void process(int value)
{
/* do something */
}
process(Multiple);
It doesn't matter what function process does; the point is it was supposed to process an int (maybe any value), not Selections. But it slipped into the code and the compiler shows no warnings and the program runs. One could probably figure other cases when the implicit conversion to int is not desired.
Strongly-typed Enums in C++ 2011
The new standard brings a new kind of enums (the existing ones are left mostly untouched - see below), introduced with 'enum class' and called strongly-typed enums. They no longer export their enumerators to the surrounding scope, can have user specified underlying type of an integral type (also added for tranditional enums) and do not convert implicitly to int.
The scope
The Selection enumeration shown earlier would be defined as:
enum class Selection
{
None,
Single,
Multiple,
};
To use it, one must use the Selection:: qualifier, because the enumerators are no longer exported to the surrounding scope (in this case the global namespace).
Selection s = Selection::Multiple;
And if we add the Border enumeration, the problem with the redefinition of None would no longer happen, since the two None names are members of different types (in different scopes).
enum class Border
{
None,
Flat,
Raised,
Sunken
};
The Underlying Type
By default, the underlying type is int and the same rules as for traditional enums apply if the user does not specify anything else. However, it is possible to do that now, but you can only use an integral type for that.
enum class Selection : unsigned char
{
None,
Single,
Multiple,
};
Since the underlying type can be specified, it will be possible to do forward declaration for enums (for the reasons explained in an earlier paragraph).
enum class Selection : unsigned char;
void make_selection(Selection s)
{
}
enum class Selection : unsigned char
{
None,
Single,
Multiple,
};
However, it is possible to specify the underlying type for traditional enums too. This is also legal in C++ 2011 (and actually supported for some years by various compilers):
enum Selection : unsigned char
{
None,
Single,
Multiple,
};
Forward declaration with traditional enums will also be possible.
Implicit Conversion
Enumerators of strongly-typed enums no longer implicitly convert to int. The following piece of code will trigger an error:
int s = Selection::Multiple;
Instead, you have to write:
Selection s = Selection::Multiple;
This would allow the compiler to immediately flag cases when the enumerators are used in place of an int (as shown earlier), which enable us to write better code.
Conclusions
The new C++ standard brings a new type of enums, referred to as strongly-typed enums and introduced with the 'enum class' keywords. They solve the known problems with the traditional enums: the scope of the enumerators, the possibility to specify the underlying type (also added for the traditional enums) and the implicit conversion to int which is not supported.

Comments
christian louboutin on sale online store for women 2013
Posted by TRereebup on 04/13/2013 06:36pm[url=http://cheapchristianlouboutinnewshoes.webs.com/]cheap christian louboutin Shoes[/url] at Think Tank have released a brand new line of camera bags after using the gripes and grumblings from the photographers community of what they wished they had in a very camera bag. Think Tank has come through having a new line of digital camera bags called the Retrospective line. hooked me up with a Think Tank 20 in black, and I spent a final two months testing the bag in many rigorous photographic situations. The green (Pinestone) bags are constructed with a soft cottom canvas, and the black [url=http://christianlouboutinmensoline.webs.com]louboutins shoes[/url] bags are made of a soft nylon poly weave. The black Retrospective bags are treated having a waterproof coating, whose actual ability to repel water can be a function I can none confirm or deny mainly because that I have not really gotten stranded out while in the rain with this case. Yet. First and foremost, the [url=http://fashionchristianlouboutinshoesuk.webs.com/]cheap christian louboutin[/url] bag is stealthy. I cannot tell how important this feature is to me. I live and work while in the large metropolitan city that is Chicago. I do not need for everyone on the street to understand that I am transporting pricey camera equipment. This function in itself is invaluable. It actually resembles some sort of plain [url=http://2014christianlouboutinoutlet.webs.com/]christian louboutin[/url] .
Reply[url=http://www.jppradaoutlet2013.com/#234534][b]ãªã¥ã㯠ãã©ã[/b][/url]
Posted by Alablisbums on 03/26/2013 04:49amThe earlier glory selling mark Burberry issued profit admonition,[url=http://www.jppradaoutlet2013.com/#234551][b]PRADA 財å¸[/b][/url] ï¼ the supermarket tortured up the prospects seeing that magnificence goods. PRADA (Prada, Hong Kong stocks 01,913),[url=http://www.jppradaoutlet2013.com/#234546][b]ãã©ã ãã¼ã[/b][/url] teeth of that, has announced the interim results, no uncertainty for the gain of the entirety peddle into a tonic. PRADA milieu in the commencing half of this year, the days in which to bring off a netting profit of 286 million euros, [url=http://www.jppradaoutlet2013.com/#234553][b]ãã©ã ãã¼ã[/b][/url] ï¼representing a eloquent year-on-year expansion of 59.5%, sales of goods of various kinds inï¼[url=http://www.jppradaoutlet2013.com/#234550][b]PRADA[/b][/url] ï¼sundry regions of the people be eternal improved dramatically, with uncommonly balanced wen in the Asia-Pacific precinct has mature into the circle's fastest-growing compass, [url=http://www.jppradaoutlet2013.com/#234543][b]PRADA[/b][/url] ,grating sales increased 44.7%. Analysts said that with superior purchasing power of Chinese consumers is fluent the perfect outstanding team of two the increase of the gigantic hedonism goods. PRADA interim be of consequence played energetic spread, but in go through,[url=http://www.jppradaoutlet2013.com/#234534][b]ãªã¥ã㯠ãã©ã[/b][/url] ï¼http://www.jppradaoutlet2013.com from mid-August, a adjustment in demo luxury brand. Media brand specializes in manufacturing compared with the low-priced products are being attacked by the smash of the economic downturn, but extension is pacific fair enough to devour the lofty motorway of number Hermes exemplary month raised its 2012 sales wen reason to 12%.
Replymichael kors wallet
Posted by michael kors wallet on 01/21/2013 01:19am[url=http://michaelkors-sales.webs.com/]micahel kors sale[/url] handbags intense SALE in michael kors sale,[url=http://michaelkors-sales.webs.com/]michael kors wallet[/url] outlet online,michael kors purses with great discounts and free shipping.Welcome to michael kors for michael kors wallet and other michael kors bags.
Replymichael kors
Posted by michael kors wallet on 01/19/2013 09:20pm[url=http://michaelkors-sales.webs.com/]micahel kors sale[/url] handbags warm up SALE in michael kors sale,[url=http://michaelkors-sales.webs.com/]michael kors purses[/url] escape online,michael kors purses with great discounts and autonomous shipping.Welcome to michael kors for michael kors wallet and other michael kors bags.
Replycanada goose jacket
Posted by canada goose jacket on 11/13/2012 08:25amntlehkavy Canada Goose Norge bdysbyewz http://canadagoosejakkerlove.com/ Canada Goose Jakker Salg yjtdgeyyw canada goose outlet qfefiywsf http://goosejacketsoutletsale.com/ canada goose jacket
Replycanada goose
Posted by canada goose on 11/13/2012 03:07amwlctfwuxi Canada Goose Jakker ujsxfsrjg http://canadagoosejakkerlove.com/ Canada Goose Parka ymbttlxof canada goose outlet jcgoebmue http://goosejacketsoutletsale.com/ canada goose jackets
Replycanada goose jacket
Posted by canada goose outlet on 11/12/2012 08:42amanfzabhjc Canada Goose uizcezhmk http://canadagoosejakkerlove.com/ Canada Goose Jakker Salg expqhquhn canada goose jacket kensmkzbj http://goosejacketsoutletsale.com/ canada goose jackets
Replycanada goose outlet
Posted by canada goose jacket on 11/11/2012 11:56pmefebeuuqa Canada Goose Jakker Salg rlsxibnzg http://canadagoosejakkerlove.com/ Canada Goose Jakker Salg vxqfcqwru canada goose parka ychuplmfm http://goosejacketsoutletsale.com/ canada goose
ReplyI was very pleased to discover this web-site
Posted by elipielry on 11/11/2012 06:03amI was more than happy to discover this web-site. I needed to many thanks for your efforts for this fantastic read!! I certainly enjoying each small dose of it and I have you bookmarked to have a look at new stuff you blog post. Moncler палÑÑо scugbotu http://www.russianmoncler.ru Moncler вниз женÑин npzdyfae пÑÑ Ð¾Ð²Ð¸ÐºÐ¸ moncler ndepcxmw Canada Goose Jackets ccswhprx http://www.mycanadagoose.com Canada Goose Parka dwroeewg Cheap Canada Goose rihfoswx Canada Goose Jackets gepidkch http://www.canadagoosesales.com Canada Goose Parka pyyowjfx Canada Goose sale ecyiygkg Piumini Moncler bscufofg http://www.okgiubbottimoncler.eu Piumini Moncler Outlet jbqwgcwu Giubbotti Moncler nzmbwrgp Canada Goose tagxnijr http://www.mincanadagoose.eu Canada Goose Jakke gpcmuqnp Billige Canada Goose Jakke erapulqp Kjøpe Canada Goose jakker pkxubcxo Canada Goose Parka wquewjbr Am I Allowed To just say what a relief to find someone who actually knows what theyre referring to online.
Replycanada goose parka
Posted by canada goose jackets on 11/10/2012 11:22pmzmdaaarlr Canada Goose Jakker Salg sryuyeqhx http://canadagoosejakkerlove.com/ Canada Goose Jakker nmrbvsslz canada goose parka onevhwxcd http://goosejacketsoutletsale.com/ canada goose jacket
ReplyLoading, Please Wait ...