Bitflag enums in C++
Asked Answered
T

4

2

Using enums for storing bitflags in C++ is a bit troublesome, since once the enum values are ORed they loose their enum-type, which causes errors without explicit casting.

The accepted answer for this question suggests overloading the | operator:

FlagsSet operator|(FlagsSet a, FlagsSet b) 
{ 
    return FlagsSet(int(a) | int(b)); 
}

I'd like to know if this method has any runtime implications?

Tsana answered 7/11, 2009 at 16:29 Comment(2)
+1 Because I didn't know this technique yet.Phratry
switch int to unsigned - otherwise you're asking for other code to end up with sign-extension issues (bit flags are never signed! that would be insanely foolish).Polston
F
5

Runtime implications in terms of correctness? No - this should be exactly what you want.

Runtime implications in terms of speed? I would expect any decent compiler to optimize this away properly to the minimal number of instructions for a release build (although you might want to add inline just to be sure).

Fanlight answered 7/11, 2009 at 16:34 Comment(1)
+1. Regarding inline: smart compilers will ignore the keyword and inline code at their discretion; it is generally useless to mark functions inline for performance reasons these days. There is, however, very much different reason to add inline, assuming the function is defined in a header file.Thorite
N
0

It potentially does three copies and a function call, barring RVO, registers, and/or inlining optimizations.

Naked bitwise OR operations themselves usually decompose to a single processor instruction.

Nine answered 7/11, 2009 at 16:35 Comment(1)
Not only is that probably not a bottleneck, but you admit yourself the compiler could be smart enough to optimize this stuff.Beam
Z
0

The code is correct.

The code will be the same speed as without type casts.

But whether the code is fast is irrelevant, because a type named 'FlagSet' will most probably be used in a context of conditionals test (-> "if (Flag)"), which is more of a hit to speed than a bit wise 'or' of two values of the size of a register.

Zounds answered 7/11, 2009 at 16:48 Comment(0)
M
0

use std::bitset for your bit flags... much simpler ;) or boost::dynamic_bitset.

Marielamariele answered 7/11, 2009 at 20:52 Comment(2)
this doesn't accomplish bit-flag usage semantics or reduce the overhead one bit! a bitset is the moral equivalent of vector<bool> which is nothing like a set of bit-flags.Polston
much shame :( - sorry, my own ignorance - bitset does indeed have bitwise operations, is not vector<bool> - I am an idiot. :(Polston

© 2022 - 2024 — McMap. All rights reserved.