macro for enum operations

Simon Hausmann hausmann at kde.org
Wed Sep 10 12:35:10 BST 2003


On Wed, Sep 10, 2003 at 01:15:12PM +0200, Lubos Lunak wrote:
> > #define K_DEFINE_ENUM_OPERATIONS( EnumType ) \
> >     inline EnumType operator^( EnumType first, EnumType second ) \
> >     { return EnumType( int( first ) ^ int( second ) ); } \
[...]
> > Thoughts/Opinions?
> 
>  s/int/unsigned long/ , I'd say

Oops, right, that makes a lot of sense.

>  Looks like a good idea, even though creating enum values that are not defined 
> in the enum feels a bit scary, as enum is usually seen as 'one value from a 
> set', but that's probably just because I'm not used to them this way.

True, it feels dirty. But on the other hand... that's the API already anyway.
It's just about making it prettier and avoiding code duplication (not defining
the operators all the time again) .

I realize the macro name is also bad. I guess this is better and
complete:

#define K_DEFINE_ENUM_BITWISE_OPERATORS( EnumType ) \
    inline EnumType operator^( EnumType lhs, EnumType rhs ) \
    { return EnumType( ulong( lhs ) ^ ulong( rhs ) ); } \
    inline EnumType operator&( EnumType lhs, EnumType rhs ) \
    { return EnumType( ulong( lhs ) & ulong( rhs ) ); } \
    inline EnumType operator|( EnumType lhs, EnumType rhs ) \
    { return EnumType( ulong( lhs ) | ulong( rhs ) ); } \
    inline EnumType operator~( EnumType lhs ) \
    { return EnumType( ~ulong( lhs ) ); } \
    inline EnumType operator^=( EnumType &lhs, EnumType rhs ) \
    { return ( lhs = EnumType( ulong( lhs ) ^ ulong( rhs ) ) ); } \
    inline EnumType operator&=( EnumType &lhs, EnumType rhs ) \
    { return ( lhs = EnumType( ulong( lhs ) & ulong( rhs ) ) ) ; } \
    inline EnumType operator|=( EnumType &lhs, EnumType rhs ) \
    { return ( lhs = EnumType( ulong( lhs ) | ulong( rhs ) ) ); } \

Simon




More information about the kde-core-devel mailing list