Native enums in C++

I always thought that enums in C++ always had the same integer as the underlying type. I discovered today that need not be the case and they can have any integral type as an underlying type. See the example below as an example.



/*
 BUILD COMMAND
 cl native_enum.cpp /EHs /wd4996 /I"<Insert boost::format path here>"

 NOTES
 I used boost::format for helping with formatting the string, You can
 replace it with printf if you like.

 Disabled warning 4996 that is a spurious warning.

 OUTPUT
    sizeof(vehicle): 1
    sizeof(creature: 2
    sizeof(home):    4
 */

#include <iostream>
#include <boost/format.hpp>
using namespace std;

enum vehicle : char { car, boat, plane };
enum creature: short { dog, cat, eagle };
enum home: int { house, apartment, mansion};
int main(int argc, char *argv[])
{
    cout<<boost::format("sizeof(vehicle): %d") % sizeof(vehicle) <<endl;
    cout<<boost::format("sizeof(creature: %d") % sizeof(creature) <<endl;
    cout<<boost::format("sizeof(home):    %d") % sizeof(home) <<endl;
    return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: