3

I switched my macro (that are bad and make small childrens scared, as Google said) to scoped enum. I think is great to have scoped enum. Then I wrote this:

if ((msg.Stamp & RECEIVERS::BROADCAST) != RECEIVERS::BROADCAST)
                 ^^^^^^^^^^^^^^^^^^^^
//do stuff

and intellisense give me a weird error like: "expression must have integral type or unscoped enum". Why I can't make that bitwise and with scoped enum?

Chaplin89
  • 175
  • 1
  • 11
  • 1
    http://stackoverflow.com/questions/8357240/how-to-automatically-convert-strongly-typed-enum-into-int – ctor May 02 '14 at 09:26

1 Answers1

2

You can, but you have to write your own operator overload

RECEIVERS operator&(RECEIVERS l, RECEIVERS r)
{
  using underlying = typename std::underlying_type<RECEIVERS>::type;
  return static_cast<RECEIVERS>(static_cast<underlying>(l) & static_cast<underlying>(r));
}

The built-in binary operator& only works with integral types and unscoped enumeration types. Scoped enumerations types have restrictions on how you can use them, they do not behave like integers, so (by default) they only support a limited set of operations.

Aside: the type name RECEIVERS looks horrible to me, what's wrong with Receivers? I don't like the convention of using ALL_CAPS for enumerator constants, but I dislike it even more for a type name.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
  • Ok, many thanks. Also, I didn't seen the previous question as @ctor pointed out. I would delete this question if I could. – Chaplin89 May 02 '14 at 09:42
  • 2
    There is a widespread convention that all caps means a macro. To second Jonathan's suggestion, I say not to violate this convention. – James Kanze May 02 '14 at 10:19
  • I deliberately avoided answering to that question because I think people spents too much time arguing on naming convention. It's just a convention. If it is consistent and bla bla bla and most of all makes me comfortable, I can't see where the problem is. Pass it over. :) – Chaplin89 May 02 '14 at 10:27
  • And, for what I understand from this question, I'm not using scoped enum anymore so: problem solved. :) – Chaplin89 May 02 '14 at 10:31
  • 1
    Good naming conventions are useful ( _"There are only two hard things in Computer Science: cache invalidation and naming things."_ -- [Phil Karlton](http://martinfowler.com/bliki/TwoHardThings.html)). Macros do not respect namespaces or other scopes, so naming conventions for macros are even more important. Reserving ALL_CAPS for macros helps avoid errors. Also, ALL_CAPS is just ugly and shouty, why do you want constants to STAND OUT from the rest of your code? Constants are boring, they don't deserve ATTENTION. Macros deserve ATTENTION. – Jonathan Wakely May 02 '14 at 11:44
  • Ok, that is your point of view and I admit that is interesting. I'll keep this in mind when I program, I promise. – Chaplin89 May 02 '14 at 12:45