Skip to content

Instantly share code, notes, and snippets.

@brimston3
Created April 29, 2016 15:53
Show Gist options
  • Select an option

  • Save brimston3/84b1382b90aeffef0459ee6d791dc3c0 to your computer and use it in GitHub Desktop.

Select an option

Save brimston3/84b1382b90aeffef0459ee6d791dc3c0 to your computer and use it in GitHub Desktop.
In C++ Anything Is Possible. The only limitation is you!
/* Demonstrate operator|() overloading for enum type.
If you want to hide the fact that your enum's numerical encoding is not actually bit flaggable.
Please don't hurt me, I promise you will never see this in production code from me.
~~aed.20160429
Runnable version:
http://coliru.stacked-crooked.com/a/bfedb189f1929447
*/
#include <stdio.h>
#include <algorithm>
enum E {
E1 = 1,
E2 = 2,
E3 = 3,
E4 = 4
};
E operator|(const E & e1, const E & e2)
{
E emin = std::min(e1,e2);
E emax = std::max(e1,e2);
if (emin == E1 && emax == E2)
{
return E3;
}
return emax;
}
int main()
{
E en = E1;
printf ("1: %d\n", en); // prove it's printable.
printf ("2: %d\n", en | E1); // basically no-op.
printf ("3: %d\n", en | E4); // pick highest.
printf ("4: %d\n", en | E2); // special case.
printf ("5: %d\n", (int)en | (int)E4); // force a different operator. cf. #3 above.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment