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.



About the Author

Marius Bancila

Marius Bancila is a Microsoft MVP for VC++. He works as a software developer for a Norwegian-based company. He is mainly focused on building desktop applications with MFC and VC#. He keeps a blog at www.mariusbancila.ro/blog, focused on Windows programming. He is the co-founder of codexpert.ro, a community for Romanian C++/VC++ programmers.

Comments

  • cheap wallets cheap wallets cheap wallets

    Posted by cheap wallets on 06/25/2013 02:09am

    ur j q p louis vuitton outlet r iqjx mx x n x authentic celine bags c vmey da a n l authentic celine bags y ebpp kv l p c wholesale designer sunglasses q rslo ya q v e wholesale sunglasses j ljca vr r e u celine bags y hmgy

    Reply
  • bargain football kits,cheap full football kits,clearance football kits

    Posted by UtteltbiseFus on 06/21/2013 06:57am

    weens and Gifts. More Details Unknown Hatley Free Shipping on 50 or more order. More Details Unknown Hatley New Clearance Section 60% off Umbrellas, Boxers, T shirts and Tank Tops. More Details Unknown Hatley Free Shipping on 50 or more order. More Details Jan 1, 2016 Hatley Free Shipping on 50 or more order. More Details Unknown HearthSong Check out [url=http://oisoccershirts.webs.com/]youth soccer jerseys[/url] HearthSong's Deal of the Week. Shop Direct Unknown HearthSong Up to 70% off in the Outlet. Shop Direct Sep 1, 2012 Heirloom Wooden Toys Save 15 when purchasing all 4 pieces of the Children's Sunflower Furniture Set. More Details Unknown Heirloom Wooden Toys Free Shipping on 99 or more order. More Details Jan 1, 2016 Heirloom Wooden Toys Free Shipping on 99 or more order. More Details Unknown Home Living Style Free Shipping on 100 or more order at Home Living Style. More Details Unknown Hooked on Phonics Free Shipping on 130 or more order. Continental U. S. Only. Shop Direct Unknown Hooked on Phonics 20% off your order. Coupon Code: SAVE20 Shop Direct Unknown Hooked on Phonics 30 day, risk Free trial on the Hooked on Phonics Learn to Read program Now: 14. 95 and Free Shipping and Free Gifts. Shop Direct Unknown Hooked on Phonics Overstock Sale Up to 70% off. Shop Direct Unknown Hooked on Phonics 20% off Sylvan Learning Reading Success Programs. Coupon Code: HOP20 Shop Direct Feb 1, 2012 Jockey. com Check out the latest markdowns for the whole family More Details Unknown Jockey. com Receive free shipping on orders of 65 or more. Plus, Free Returns on all orders. More Details Unknown Jockey. com Free Shipping on 75 or [url=http://oisoccershirts.webs.com/]wholesale soccer jerseys[/url] more order, and Free returns. More Details Unknown JoggingStroller. com Free shipping on 99 or more order. More Details Unknown Kee Ka Free Shipping on 75 or more order. Continental U. S. Only. More Details Unknown KimmyShop Free Shipping on 99 or more orders. Continental U. S. Only. More Details Unknown KimmyShop Super Sale Items Up to 75% off. More Details Unknown Kitsel Grab Where the Wild Things Are Appar

    Reply
  • mulberry bags

    Posted by mulberry bags on 06/15/2013 12:31am

    new balance 623 review new balance 625 new balance 645 new balance 646 new balance 650 new balance 655 new balance 663 new balance 670 red devil new balance 710 new balance 738 new balance 740 new balance 755 new balance 756 new balance 758 new balance 759 new balance 760 new balance 766 new balance 767 new balance 768 new balance 769 new balance 770 new balance 773 new balance 790 new balance 800 new balance 801 new balance 805 new balance 810 new balance 811 new balance 811 women new balance 812 new balance 813 new balance 817 new balance 826 new balance 840 new balance 845 new balance 846 new balance 847 new balance 847 women new balance 850 new balance 8505 new balance 851 new balance 854 new balance 856 new balance 857 new balance 859 new balance 860 new balance 860 review new balance 860v3 new balance 870 new balance 871

    Reply
  • myufujfpz

    Posted by Allonnanvam on 06/10/2013 10:28am

    スナップオン www.mcmmore.com mcm,mcm リュック,mcm 財布,mcm バッグ,mcm 長財布 Snapon MCM mcm,mcm リュック,mcm 財布,mcm バッグ,mcm 長財布 デッドブロー 無反動ボールピーンハンマー品番 MCM リュック mcm,mcm リュック,mcm 財布,mcm バッグ,mcm 長財布 HBBD16(450g)重量 450グラムカラー選択 赤、オレンジ、グリーン全長 コーチ バッグ コーチ財布,コーチ アウトレット,コーチバッグ,コーチ,COACH 31cmヘッド部高さ 11cmヘッド部直径 3cmヘッド部には細かい鉛玉が入っており、ほとんど跳ね返りが有りません。無反動タイプで無い通常のハンマーより40増しで打撃できます。重く無く、軽く無く大変持ったときのバランスの良いハンマーで扱い易く疲れません。 彼女のキャリアを通じて、アークエットは、テレビとスクリーンの映画に出演しています。 コーチ メンズ コーチ財布,コーチ アウトレット,コーチバッグ,コーチ,COACH 1982年に、彼女はテレビ映画エグゼキュショナーソングエミー賞のノミネートを獲得した。その後、彼女は多くの映画の映画やテレビ映画でプレイ最後の20年間で最も高い評価を映画監督の多くが働いています。 軽やかなキルティングを主素材に使用したラグジュアリー・ライフスタイルブランドVera Bradley[ベラブラッドリー]から、トートバッグが入荷しました。シンプルなシルエット、内側の3つのポケット、余裕で肩にかけられる長めのストラップ等、機能的で毎日にしっくりなじむアイテム。べっ甲柄のトグルで開閉できます。

    Reply
  • 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:49am

    The 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%.

    Reply
  • michael 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.

    Reply
  • michael 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.

    Reply
  • canada goose jacket

    Posted by canada goose jacket on 11/13/2012 08:25am

    ntlehkavy Canada Goose Norge bdysbyewz http://canadagoosejakkerlove.com/ Canada Goose Jakker Salg yjtdgeyyw canada goose outlet qfefiywsf http://goosejacketsoutletsale.com/ canada goose jacket

    Reply
  • canada goose

    Posted by canada goose on 11/13/2012 03:07am

    wlctfwuxi Canada Goose Jakker ujsxfsrjg http://canadagoosejakkerlove.com/ Canada Goose Parka ymbttlxof canada goose outlet jcgoebmue http://goosejacketsoutletsale.com/ canada goose jackets

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • You probably have several goals for your patient portal of choice. Is "community" one of them? With a bevy of vendors offering portal solutions, it can be challenging for a hospital to know where to start. Fortunately, YourCareCommunity helps ease the decision-making process. Read this white paper to learn more. "3 Ways Clinicians can Leverage a Patient Portal to Craft a Healthcare Community" is a published document owned by www.medhost.com

  • When it comes to desktops – physical or virtual – it's all about the applications. Cloud-hosted virtual desktops are growing fast because you get local data center-class security and 24x7 access with the complete personalization and flexibility of your own desktop. Organizations make five common mistakes when it comes to planning and implementing their application management strategy. This eBook tells you what they are and how to avoid them, and offers real-life case studies on customers who didn't let …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds