1 #ifndef DALI_BITWISE_ENUM_H
2 #define DALI_BITWISE_ENUM_H
5 * Copyright (c) 2018 Samsung Electronics Co., Ltd.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
20 #include <type_traits> // std::enable_if, std::underlying_type
26 * Type traits and methods to enable type safe bit field operators for an enum.
28 * template<> struct EnableBitMaskOperators< MyEnumType > { static const bool ENABLE = true; };
29 * after this one can set bitfields with | and |=, like
30 * MyEnumType value = FLAG1 | FLAG2;
31 * and test them with &, like:
32 * if( myFlag & FLAG2 )
35 template< typename Enum >
36 struct EnableBitMaskOperators
38 static const bool ENABLE = false; // can't be constexpr as it's a data member
42 * Combine two bitfields
43 * @param lhs bitfield to or
44 * @param rhs bitfield to or
45 * @return EnumType with both flags set
47 template < typename EnumType >
48 inline typename std::enable_if< EnableBitMaskOperators< EnumType >::ENABLE, EnumType >::type operator|( EnumType lhs, EnumType rhs )
50 using UnderlyingType = typename std::underlying_type<EnumType>::type;
51 return static_cast<EnumType>( static_cast<UnderlyingType>( lhs ) | static_cast<UnderlyingType>(rhs ) );
55 * Combine two bitfields
56 * @param lhs bitfield to or
57 * @param rhs bitfield to or
58 * @return reference to lhs with both flags set
60 template < typename EnumType >
61 inline typename std::enable_if< EnableBitMaskOperators< EnumType >::ENABLE, EnumType& >::type operator|=( EnumType& lhs, EnumType rhs )
63 using UnderlyingType = typename std::underlying_type<EnumType>::type;
64 lhs = static_cast<EnumType>(static_cast<UnderlyingType>( lhs ) | static_cast<UnderlyingType>( rhs ) );
70 * @param lhs bitfield to AND
71 * @param rhs bitfield to AND
72 * @return true if at least one flag is same in both
74 template < typename EnumType >
75 inline typename std::enable_if< EnableBitMaskOperators< EnumType >::ENABLE, bool >::type operator&( EnumType lhs, EnumType rhs )
77 using UnderlyingType = typename std::underlying_type<EnumType>::type;
78 return static_cast<bool>( static_cast<UnderlyingType>( lhs ) & static_cast<UnderlyingType>(rhs ) );
83 #endif // DALI_BITWISE_ENUM_H