Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this colon do in an enum declaration?

Tags:

c++

enums

I did a search for this question thinking that somebody must have asked it before. I did not turn up any results, so if it has been, please post the link and feel free to close the question.

I ran across this code in EASTL:

enum : size_type {   // size_type = size_t                   
                npos     = (size_type)-1,
                kMaxSize = (size_type)-2
            };

I have never encountered an enum declaration like that. What does the : do in this case?

like image 730
Samaursa Avatar asked Jun 27 '11 17:06

Samaursa


People also ask

What is the use of a colon in a class declaration?

There are three distinct usages of a colon in the declaration of a class. The third is to use generic constraints (happens at a different place but still in declaration) There are two colons used in class declarations. The most common one denotes inheritance:

Which is an example of enum declaration?

Following is an example of enum declaration. // The name of enumeration is "flag" and the constant // are the values of the flag. By default, the values // of the constants are as follows: // constant1 = 0, constant2 = 1, constant3 = 2 and // so on. enum flag {constant1, constant2, constant3, ....... };

What is the use of enum in C++?

It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. The keyword ‘enum’ is used to declare new enumeration types in C and C++. Following is an example of enum declaration. // The name of enumeration is "flag" and the constant // are the values of the flag.

What is enumeration in C++?

Last Updated : 21 Dec, 2018. Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain. enum State {Working = 1, Failed = 0}; The keyword ‘enum’ is used to declare new enumeration types in C and C++.


2 Answers

In C++0x, you can specify the underlying type for the enum. In this case, it will be size_type.

(And it may be supported as an extension in other places prior to C++0x, obviously.)

like image 119
GManNickG Avatar answered Oct 29 '22 13:10

GManNickG


This is a Microsoft extension that lets you choose the base type of the enum values. For example, this lets you specify that values are unsigned (Microsoft's compilers usually choose signed by default) or that they only occupy 8 or 16 bits (Microsoft normally defaults to 32 bits).

The syntax is documented here: http://msdn.microsoft.com/en-us/library/2dzy4k6e(v=VS.100).aspx but I'm not able to find official documentation of what it actually does.

C++11 adds a similar feature, but with slightly different syntax. In C++11 you'd write it like this:

enum MyEnum : size_type { .. values .. };
like image 40
Jesse Hall Avatar answered Oct 29 '22 15:10

Jesse Hall