天天看點

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)
    {
    }

}      

繼續閱讀