Enumarator中的按位运算

时间:2018-11-25 06:32:31

标签: c++ c++11

我需要根据情况将一些额外的数据添加到现有的枚举代码中。作为示例,我具有以下代码:

// Full Code
#include <iostream>
#include <memory>
#include <chrono>

class Timer {
    using clock = std::chrono::system_clock;
    double cumulative_time{};
    double interval_time{};
    clock::time_point snapshot_time{ clock::now() }, tmp;
public:
    void start() { snapshot_time = clock::now(); }
    void reset() { cumulative_time = 0; start(); }
    double get_interval_time() {
        cumulative_time += (interval_time = std::chrono::duration<double>((tmp = clock::now()) - snapshot_time).count());
        snapshot_time = tmp;
        return interval_time;
    }
    double get_cumulative_time() {
        cumulative_time += std::chrono::duration<double>((tmp = clock::now()) - snapshot_time).count();
        snapshot_time = tmp;
        return cumulative_time;
    }
};

template<typename T>
void fill(T &v, int len) {
    int i = 0;
    for (int i = 0; i < len; i++)
        v[i] = i;
}


using namespace std;

#define TYPEMOD  //__restrict // Uncomment to add __restrict
void f1(int * TYPEMOD p1, int * TYPEMOD p2, int count)
{
    for (int i = 1; i < count - 1; i++)
        p2[i] = p1[i - 1] + p1[i + 1];
}

void f2(std::unique_ptr<int[]>& TYPEMOD p1, std::unique_ptr<int[]>& TYPEMOD p2, int count)
{
    for (int i = 1; i < count - 1; i++)
        p2[i] = p1[i - 1] + p1[i + 1];
}


auto xf1 = f1;  // avoid inlining
auto xf2 = f2;


int main() {
    const int N = 100'000'000;
    auto pa = new int[N]; fill(pa, N);
    auto ptra = std::make_unique<int[]>(N); fill(ptra, N);

    Timer timer;
    xf1(pa, pa, N);
    auto snap1 = timer.get_interval_time();
    xf2(ptra, ptra, N);
    auto snap2 = timer.get_interval_time();
    std::cout << "Raw pointer data " << pa[0] << pa[1] << pa[2] << pa[3] << "  time " << snap1 << "\n";
    std::cout << "Unique_ptr  data " << ptra[0] << ptra[1] << ptra[2] << ptra[3] << "  time " << snap2 << "\n";
    std::cout << "\n";
}

起初,我尝试添加数据,然后提取相同的数据-但出现编译错误:

#include <iostream>

enum Permissions {Readable = 0x4, Writable = 0x2, Executable = 0x1};

int main()
{
Permissions perms = static_cast<Permissions>(Executable | static_cast<Permissions>(29));
std::cout << perms  <<  std::endl;
perms &= ~Permissions::Executable;
std::cout << perms  <<  std::endl;
}

方法正确吗?如何消除编译错误?

1 个答案:

答案 0 :(得分:3)

  

方法正确吗?如何消除编译错误?

该方法存在问题。如果您仔细使用变量,则可以使用self.name

podspec

等同于

enum

导致编译器错误的原因是按位运算符会导致perms &= ~Permissions::Executable; ,而您试图将perms = perms & ~Permissions::Executable; 分配给int而没有强制转换。

您必须像执行第一个操作一样使用强制转换来摆脱编译器错误。

int

更新,以回应OP的评论

enumperms = static_cast<Permissions>(perms & ~Permissions::Executable); ,它与Readable | Writable中任何令牌的值都不对应。 因此,如果您使用:

0x6

您将遇到enum的值与任何已知标记都不匹配的情况。如果您有Permissions p1 = Permissions::Readable; Permissions p2 = Permissions::Writable; Permissions p3 = static_cast<Permissions>(p1 | p2); / p3块或if语句期望else类型的所有变量的值是已知标记之一,则您会注意到您的代码。