Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are "enum class" members instantiated immediately or later when used?

Tags:

c++

c++11

Consider this one

template<typename T>
struct A {
  enum class X {
    V = T()
  };
};

For member classes and member functions, C++11 (and C++03) won't instantiate their definition unless we use them in a way that requires their definition. Is this true for enum class?

// valid?
A<std::string> a;

Unfortunately, I can't check compilers, since C++11 is just out of the door and everything isn't reliable yet, it seems.

like image 868
Johannes Schaub - litb Avatar asked Oct 16 '11 21:10

Johannes Schaub - litb


People also ask

Can enum class be instantiated?

You need to access toString() using any of these static instances or make the toString method static to have it accessible through CustomerType class. No, you cannot instantiate enums, and there's a good reason for that. Enums are for when you have a fixed set of related constants.

How are enums initialized in Java?

You can't create an instance of Enum using new operators. It should have a private constructor and is normally initialized as: ErrorCodes error = ErrorCodes. BUSSINESS_ERROR. Each constant in the enum has only one reference, which is created when it is first called or referenced in the code.

Do enums always start at 0?

If the first enumerator has no initializer, the value of the corresponding constant is zero. An enumerator-definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumerator by one. So yes, if you do not specify a start value, it will default to 0.

Are enum members static?

The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).


1 Answers

I think so. 14.7.1/1

The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of [...] scoped member enumerations

like image 70
Alan Stokes Avatar answered Sep 25 '22 06:09

Alan Stokes