Last Updated: February 25, 2016
·
1.841K
· alexanderbrevig

Simulated type safe enums with C++

Hi guys!

I want enums that provide useful error messages, and allows for a name to be part of many types.

enum STATE { ON };
enum MOTOR { ON }:

The above would complain about name collisions.

Given this method:

void onlyOnOff(ON_OFF on){
   if (on == ON){
         //do something
   }else {
         //do something else
   }
}

I want a compiler error in failure to supply either ON or OFF to onlyOnOff.

Let's investigate my solution:
With the below implementation of classes and constants, this works.

If I pass anything other than ON or OFF to onlyOnOff I get an error message like this:
'onlyOnOff' : cannot convert parameter 1 from '<type>' to 'ON_OFF '

class ON_OFF_ {}; typedef const ON_OFF_* const ON_OFF;

class ON_ : public ON_OFF_{}; 
const ON_ on_; const ON_ * const ON = &on_;

class OFF_ : public ON_OFF_{}; 
const OFF_ off_; const OFF_ * const OFF = &off_;

1 Response
Add your response

There is lots of other solutions which are IMHO nicer as they do not require global variables with static storage duration.

For example https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Type_Safe_Enum

over 1 year ago ·