gpt4 book ai didi

c++ - 如何使 0 自动转换为枚举? (|= 有效但无效 =)

转载 作者:行者123 更新时间:2023-12-05 09:06:59 27 4
gpt4 key购买 nike

如果您看一下下面的代码,您会发现我重载了 |= 以允许与整数进行 ORing。但是我不知道如何重载 =。 Clang 似乎说我需要 = 在枚举体中并且枚举体不能有重载。所以我很困惑,这似乎是不可能的?

我主要希望 0 成为 Test 的可接受值 我实际上并不需要转换所有整数,但如果它们是(也许我稍后会这样做)也没关系

我正在使用 C++ 20

#include <cstdio>

enum Test {
Test_NA,
one, two, three
};

inline Test& operator |= (Test&a, int b) { return a =(Test)(a|b); }

int mytest(Test v) {
return v == Test_NA ? 11 : v == three ? 33 : v;
}

int main() {
Test val = two;
printf("%d\n", mytest(val));
val|=1;
printf("%d\n", mytest(val));
printf("%d\n", mytest(one));
printf("%d\n", mytest(0)); //Error here
}

最佳答案

How do I make 0 auto cast to an enum? (|= works but not =)

您不能使整数隐式转换为枚举,也不能为非类(例如枚举)定义非复合赋值运算符。复合赋值对于枚举来说是可重载的,这让我感到有点惊讶。

So I'm confused and it seems impossible?

让我来澄清你的困惑:它看起来就是这样;你正在尝试的是不可能的。

您可以改用显式转换:

mytest(static_cast<Test>(0))

关于c++ - 如何使 0 自动转换为枚举? (|= 有效但无效 =),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65416243/

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