【问题标题】:Manipulating Bits of Any Value Type操作任何值类型的位
【发布时间】:2014-01-26 20:18:39
【问题描述】:

是否有人编写了一些通用函数来扩展core.bitop bitmanipulations 以适用于任何值类型?

类似

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 在所有具有值语义的类型上工作。这就是为什么我需要演员(我认为)。是否有特征来检查类型是否具有值语义?

还有一个特征来检查一个类型是否支持特定的操作,比如按位和&amp;?我总是可以使用__traits(compiles, ...),但标准化很好。

为了让它变得更好,我想我需要一个支持位操作的 T 的显式重载,以便使这个变体@safe 对吗?在我上面的通用解决方案中,我需要cast,那就是@unsafe。

另请参阅:http://forum.dlang.org/thread/tekrnzkemcbujbivvfpv@forum.dlang.org#post-tekrnzkemcbujbivvfpv:40forum.dlang.org

【问题讨论】:

  • 无论你做什么都是不安全的,因为你可能会通过设置任意位来破坏类型的不变量
  • 位数组怎么样,如果你做一个联合,它是否适合你的目的? dlang.org/phobos/std_bitmanip.html#.BitArray

标签: bit-manipulation d bit phobos


【解决方案1】:

是否有特征来检查类型是否具有值语义?

值类型没有特征,至少在the documentation 中没有 但是,我在使用“is 表达式”之前检查了值类型:

import std.stdio;

struct Foo {}

auto fn(T)(T type)
{
    static if (is(T == struct)) {
        writeln(T.stringof ~ " is a value type");   
    } else if (is(T == class)) {
        writeln(T.stringof ~ " is a reference type");   
    } else {
        writeln(T.stringof ~ " is something else"); 
    }
}

void main()
{
    Foo f;

    fn(f);
    fn(new Object());
    fn(1);
}

还有一个 trait 可以检查一个类型是否支持特定的操作 比如按位和&?

除了用于编译的 trait 之外,这也可以通过 is 表达式来实现。这类似于目前对ranges, for example 的处理方式:

import std.stdio;

struct Foo {
    auto opBinary(string op)(Foo rhs) 
        if (op == "&")
    {
        return rhs.init; // dummy implementation
    }
};

template canUseBitOps(T)
{
    enum bool canUseBitOps = is(typeof(
    (inout int = 0)
    {
        T t1 = T.init;
        T t2 = T.init;
        auto r = t1 & t2;
    }));
}

void main()
{
    assert(canUseBitOps!int);
    assert(!canUseBitOps!string);
    assert(canUseBitOps!Foo);
}

【讨论】:

    【解决方案2】:

    我在https://github.com/atilaneves/cerealed 的序列化库中做了类似的事情。这不是您所要求的,但您可能会从中得到一些想法。

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 2019-10-02
      • 2014-01-18
      • 1970-01-01
      相关资源
      最近更新 更多