天天看点

d重载操作符

​​原文​​

struct Struct
{
    void opOpAssign(string op)(Struct rhs)
//在此实现`/=`.
    {
        //...
    }
}
unittest
{
   Struct a = Struct(1);
   Struct b = Struct(2);
   a /= b;
   assert(a == Struct(5, 0, -1));
}      

单元测试,不管用.

但如下,通过测试:

struct S {
    int n;
    void opOpAssign(string op)(S rhs) if (op == "/") {
        n++;
    }
}

unittest {
    auto a = S(1), b = S(2);
    a /= b;
    b /= a;
    assert(a.n == 2);
    assert(b.n == 3);
}      

问题是,根据未调用​

​opOpAssign​

​​,为什么?

可能:

struct S {
    int n;
    void opOpAssign(string op)(S rhs) if (op == "/=") {
        n++;
    }
    void opOpAssign(string op)(S rhs) if (op == "/") {
        // 闲着
    }
}

unittest {
    auto a = S(1), b = S(2);
    a /= b;
    b /= a;
    assert(a.n == 2);
    assert(b.n == 3);
}      

可用​

​-vcg-ast​

​​,让​

​编译器​

​​告诉你实际​

​调用​

​的是什么.

输出,用途不大:

unittest
{
    S a = S(1);
    S b = S(2);
    a.opOpAssign(b);
    b.opOpAssign(a);
    assert(a.n == 2);
    assert(b.n == 3);
}      

最后,只有1个实例化:

opOpAssign!"/"
{
    pure nothrow @nogc @safe void opOpAssign(S rhs)
    {
    }

}      

我希望包括​

​模板参数​

​​!我相信它通常会?应该​

​提交​

​错误.应该提出增强请求:

void foo(string s, T)(T t) {}

void main()
{
   foo!"hi"(1);
}
//输出:

void foo(string s, T)(T t)
{
}
void main()
{
    foo(1);
    return 0;
}      
import object;
void foo(string s, T)(T t)
{
}
void main()
{
    foo(1);
    foo(1);
    foo(1);
    return 0;
}
mixin _d_cmain!(); // 为了简单,省略了.
foo!("hi", int)
{
    pure nothrow @nogc @safe void foo(int t)
    {
    }

}

foo!("bar", int)
{
    pure nothrow @nogc @safe void foo(int t)
    {
    }

}      

继续阅读