gpt4 book ai didi

c++ - 将枚举类的值用于移位运算符

转载 作者:行者123 更新时间:2023-11-30 02:16:48 28 4
gpt4 key购买 nike

以下片段...

enum class A {
X = 0, Y = 1, Z = 2,
};

int s = (1 << A::X);

...产生以下编译错误:

error C2678: binary '<<': no operator found which takes a 
left-hand operand of type 'int'
(or there is no acceptable conversion)

使这种移位工作的最好和最干净的方法是什么?

最佳答案

一个小的效用函数可能有助于在保证正确性的同时澄清意图:

#include <type_traits>

template<class Enum>
auto to_bitmask(Enum e)
{
using type = std::underlying_type_t<Enum>;
return 1 << type(e);
};

https://godbolt.org/z/_pp7VW

对于更通用的版本,c++17 允许轻松处理任何枚举或整数类型:

template<class Enum>
constexpr auto to_bitmask(Enum e)
{
static_assert(std::is_integral<Enum>() || std::is_enum<Enum>());

if constexpr (std::is_enum<Enum>())
{
using type = std::underlying_type_t<Enum>;
return 1 << type(e);
}
else
{
return 1 << e;
}
}

关于c++ - 将枚举类的值用于移位运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54397785/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com