且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在布尔上下文中使用枚举类?

更新时间:2023-01-13 14:20:57


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

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.