是否有人编写了一些通用函数来扩展core.bitop
位操作以适用于任何值类型?
就像是
bool getBit(T)(in T a, int bitnum); // bt
T setBit(T)(in T a, int bitnum); // bts
auto ref setBitInPlace(T)(ref T a, int bitnum);
我知道这相对容易实现,所以我很好奇为什么它还不是 Phobos。
更新:
这是我的第一次尝试:
bool getBit(T, I)(in T a, I bitnum) @safe pure nothrow if (isIntegral!T &&
isIntegral!I) {
return a & (((cast(I)1) << bitnum)) ? true : false;
}
bool getBit(T, I)(in T a, I bitnum) @trusted pure nothrow if ((!(isIntegral!T)) &&
isIntegral!I) {
enum nBits = 8*T.sizeof;
static if (nBits == 8) alias I = ubyte;
else static if (nBits == 16) alias I = ushort;
else static if (nBits == 32) alias I = uint;
else static if (nBits == 64) alias I = ulong;
return (*(cast(I*)&a)).getBit(bitnum); // reuse integer variant
}
alias bt = getBit;
我的想法是getBit
处理所有具有值语义的类型。这就是为什么我需要演员表(我认为)。是否有特征来检查类型是否具有值语义?
还有一个特征可以检查一个类型是否支持特定的操作,比如按位和&
?我总是可以使用__traits(compiles, ...)
,但标准化很好。
为了让它变得更好,我想我需要一个支持位操作的 T 的显式重载,以使这个变体@safe 对吗?在我上面的通用解决方案中,我需要cast
@unsafe。