如何使用枚举类作为一组标志?

Bil*_*eal 12 c++ c++11

假设我有一组标志和类似这样的类:

/// <summary>Options controlling a search for files.</summary>
enum class FindFilesOptions : unsigned char
{
    LocalSearch = 0,
    RecursiveSearch = 1,
    IncludeDotDirectories = 2
};

class FindFiles : boost::noncopyable
{
    /* omitted */
public:
    FindFiles(std::wstring const& pattern, FindFilesOptions options);
    /* omitted */
}
Run Code Online (Sandbox Code Playgroud)

我希望调用者能够选择多个选项:

FindFiles handle(Append(basicRootPath, L"*"),
    FindFilesOptions::RecursiveSearch | FindFilesOptions::IncludeDotDirectories);
Run Code Online (Sandbox Code Playgroud)

是否可以使用C++ 11以强类型方式支持它enum class,或者我是否必须恢复为无类型枚举?

(我知道调用者可以static_cast使用底层类型并static_cast返回,但我不希望调用者必须这样做)

Die*_*ühl 12

当然可以将enum classes用于位图.不幸的是,这样做有点痛苦:您需要在类型上定义必要的位操作.下面是一个如何看起来的例子.如果enum classes可以从某些其他类型派生出来,那将是很好的,这些类型可以存在于定义必要的运算符样板代码的合适的命名空间中.

#include <iostream>
#include <type_traits>

enum class bitmap: unsigned char
{
    a = 0x01,
    b = 0x02,
    c = 0x04
};

bitmap operator& (bitmap x, bitmap y)
{
    typedef std::underlying_type<bitmap>::type uchar;
    return bitmap(uchar(x) & uchar(y));
}

bitmap operator| (bitmap x, bitmap y)
{
    typedef std::underlying_type<bitmap>::type uchar;
    return bitmap(uchar(x) | uchar(y));
}

bitmap operator^ (bitmap x, bitmap y)
{
    typedef std::underlying_type<bitmap>::type uchar;
    return bitmap(uchar(x) ^ uchar(y));
}

bool test(bitmap x)
{
    return std::underlying_type<bitmap>::type(x);
}

int main()
{
    bitmap v = bitmap::a | bitmap::b;
    if (test(v & bitmap::a)) {
        std::cout << "a ";
    }
    if (test(v & bitmap::b)) {
        std::cout << "b ";
    }
    if (test(v & bitmap::c)) {
        std::cout << "c ";
    }
    std::cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)

  • @SheaLevy那么没有值为"0x03"的枚举器,但是`0x03`是`bitmap`类型变量的"有效"值,请参阅http://stackoverflow.com/q/18195312/420683 (3认同)
  • 顺便说一句,正确的术语是"位域",而不是"位图".位图,尤其是图像圈中的位图,是完全不同的. (2认同)