Support just landed for two new C++11 features in MFBT:

https://bugzilla.mozilla.org/show_bug.cgi?id=751554

They're described in this paper:

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf

In brief, this lets you do two new things.  One is you can use MOZ_ENUM_TYPE() 
to specify the underlying type of an enum, like so:

  enum Foo MOZ_ENUM_TYPE(PRUint8) { A, B };

This instructs the compiler to allocate only one byte of storage for Foo, to 
save space.  Otherwise, the compiler is entitled to allocate anywhere from one 
byte to the size of an int, and gcc in practice will allocate four bytes.  
Compilers that support this include gcc 4.4 and up, Clang 2.9 and up, and VC++ 
2005 and up.  On other compilers, it will have no effect.

The other is to define "enum classes", a.k.a. strongly-typed or scoped 
enumerations.  This is done as follows:

  MOZ_BEGIN_ENUM_CLASS(Foo, PRUint8)
    A, B
  MOZ_END_ENUM_CLASS(Foo)

This makes Foo one byte, as before (the size argument is mandatory).  It has 
two further effects.  One is that Foo will not be implicitly converted from 
*or* to any numeric type, including bool -- normal enums are implicitly 
converted to numeric types, although not from.  This ensures better 
type-safety.  The other is that the enumerators ("A" and "B" here) will be 
scoped with the enum's name rather than being in the global scope, like class 
members.  Thus "A" and "B" no longer refer to anything -- you need to write 
"Foo::A" and "Foo::B".  Often enums are put in classes to avoid namespace 
pollution, but this is no longer necessary with enum classes.

Compilers that support scoped enumerations include gcc 4.4 and up, Clang 2.9 
and up, and VC++ 2011 and later.  In compilers that don't support the feature 
natively, a workaround using a regular enum nested in a class is used.  This 
will give the same scoping behavior, but not as much type safety.

Using enum classes for all new enums is encouraged, in order to avoid 
accidental conversions to other types.  It does mean that implicit conversion 
to boolean is not allowed, even though sometimes you do want it (if the 0 value 
is "none").  As a partial workaround, you can define an overloaded operator! 
for your enum class, so !enumVal and !!enumVal will still work.  C++ permits 
overloaded operators for enums and enum classes, but unfortunately not implicit 
type conversions.
_______________________________________________
dev-platform mailing list
dev-platform@lists.mozilla.org
https://lists.mozilla.org/listinfo/dev-platform

Reply via email to