Files
myxlib/src/myx/base/enum_bitmask_operations.hpp

58 lines
1.3 KiB
C++

#ifndef MYX_BASE_ENUM_BITWISE_OPERATIONS_HPP_
#define MYX_BASE_ENUM_BITWISE_OPERATIONS_HPP_
#pragma once
#include <type_traits>
namespace myx {
namespace base {
template< typename Enum >
struct EnableBitMaskOperators
{
static const bool k_Enable = false;
};
template< typename Enum >
typename std::enable_if< EnableBitMaskOperators< Enum >::k_Enable, Enum >::type
operator |( Enum lhs, Enum rhs )
{
using Underlying = typename std::underlying_type< Enum >::type;
return( static_cast< Enum >(
static_cast< Underlying >( lhs ) |
static_cast< Underlying >( rhs )
) );
}
} // namespace base
} // namespace myx
/**
* @brief Макрос, предоставляющий возможность выполнять битовые операции в enum class
*
* Источник: http://blog.bitwigglers.org/using-enum-classes-as-type-safe-bitmasks/
* Пример использования:
*
* namespace ns {
* enum class Permissions
* {
* Readable = 0x4,
* Writeable = 0x2,
* Executable = 0x1
* };
* }
* ENABLE_BITMASK_OPERATORS(ns::Permissions)
*/
#define ENABLE_BITMASK_OPERATORS( x ) \
template<> \
struct myx::base::EnableBitMaskOperators< x > \
{ \
static const bool k_Enable = true; \
};
#endif // ifndef MYX_BASE_ENUM_BITWISE_OPERATIONS_HPP_