如何在布尔上下文中使用枚举类? [英] How can I use an enum class in a boolean context?

查看:84
本文介绍了如何在布尔上下文中使用枚举类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些通用代码,这些通用代码可与使用C ++ 11 enum class 类型指定的标志一起使用。第一步,我想知道是否设置了标志中的任何位。目前,我正在使用以下代码:

I have some generic code that works with flags specified using C++11 enum class types. At one step, I'd like to know if any of the bits in the flag are set. Currently, I'm using the code:

if (flags != static_cast<E>(0)) // Works, but ugly.

我也可以强制用户为全零字段指定一个特定的名称,这样更易​​读但是将我的命名约定强加于使用它的任何人:

I could also force users to specify a particular name for an all-zero field, which is more readable but imposes my naming conventions on anyone using it:

if (flags != E::none) // Works, if you manually define none = 0.

但是,这两个方法都不像传统方法那样好读:

But neither of these reads as nicely as the traditional:

if (flags) // Doesn't work with class enums.

是否可以指定自定义函数来评估布尔上下文中的类枚举?

Is it possible to specify a custom function to evaluate a class enum in a boolean context?

推荐答案


是否可以指定一个自定义函数来评估布尔上下文中的类枚举?

Is it possible to specify a custom function to evaluate a class enum in a boolean context?

是的,但不是自动的。手动调用一个函数仍然比提供的其他替代方法更优雅。

Yes, but not automatically. Manually calling a function is still more elegant than the other alternatives presented.

只需选择一个不错的函数名称,例如 any ,并实施它。重载解析将确保您的函数与所有其他函数配合良好。

Simply pick a nice function name, such as any, and implement it. Overload resolution will make sure your function plays well with all others.

bool any( E arg )
    { return arg != E::none; }

...

if ( any( flags ) ) {
    ...

对我来说看起来不错。

更新::如果您希望将其应用于多种枚举类型,则可以将其用作模板:

Update: if you want this to apply to several enumeration types, it can be templated:

template< typename enum_type > // Declare traits type
struct enum_traits {}; // Don't need to declare all possible traits

template<>
struct enum_traits< E > { // Specify traits for "E"
    static constexpr bool has_any = true; // Only need to specify true traits
};

template< typename enum_type > // SFINAE makes function contingent on trait
typename std::enable_if< enum_traits< enum_type >::has_any,
    bool >::type
any( enum_type e )
    { return e != enum_type::none; }

我在其他事情上一直使用这种机制,从未遇到任何副作用或问题:v)。

I've been using this sort of mechanism for other things and never encountered any side effects or issues :v) .

您可以跳过特征并将SFINAE条件设置为 enum_type :: none == enum_type :: none ,仅检查 none 和相等运算符的存在,但这将不太明确和安全。

You could skip the trait and set the SFINAE condition to something like enum_type::none == enum_type::none, to merely check for the presence of none and the equality operator, but that would be less explicit and safe.

这篇关于如何在布尔上下文中使用枚举类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆