1 #ifndef DALI_BITWISE_ENUM_H
2 #define DALI_BITWISE_ENUM_H
5 * Copyright (c) 2020 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
25 * Type traits and methods to enable type safe bit field operators for an enum.
27 * template<> struct EnableBitMaskOperators< MyEnumType > { static const bool ENABLE = true; };
28 * after this one can set bitfields with | and |=, like
29 * MyEnumType value = FLAG1 | FLAG2;
30 * and test them with &, like:
31 * if( myFlag & FLAG2 )
34 template<typename Enum>
35 struct EnableBitMaskOperators
37 static const bool ENABLE = false; // can't be constexpr as it's a data member
41 * Combine two bitfields
42 * @param lhs bitfield to or
43 * @param rhs bitfield to or
44 * @return EnumType with both flags set
46 template<typename EnumType>
47 inline typename std::enable_if<EnableBitMaskOperators<EnumType>::ENABLE, EnumType>::type operator|(EnumType lhs, EnumType rhs)
49 using UnderlyingType = typename std::underlying_type<EnumType>::type;
50 return static_cast<EnumType>(static_cast<UnderlyingType>(lhs) | static_cast<UnderlyingType>(rhs));
54 * Combine two bitfields
55 * @param lhs bitfield to or
56 * @param rhs bitfield to or
57 * @return reference to lhs with both flags set
59 template<typename EnumType>
60 inline typename std::enable_if<EnableBitMaskOperators<EnumType>::ENABLE, EnumType&>::type operator|=(EnumType& lhs, EnumType rhs)
62 using UnderlyingType = typename std::underlying_type<EnumType>::type;
63 lhs = static_cast<EnumType>(static_cast<UnderlyingType>(lhs) | static_cast<UnderlyingType>(rhs));
69 * @param lhs bitfield to AND
70 * @param rhs bitfield to AND
71 * @return true if at least one flag is same in both
73 template<typename EnumType>
74 inline typename std::enable_if<EnableBitMaskOperators<EnumType>::ENABLE, bool>::type operator&(EnumType lhs, EnumType rhs)
76 using UnderlyingType = typename std::underlying_type<EnumType>::type;
77 return static_cast<bool>(static_cast<UnderlyingType>(lhs) & static_cast<UnderlyingType>(rhs));
82 #endif // DALI_BITWISE_ENUM_H