...ing logging 4.0

はてなブログに移行しました。D言語の話とかいろいろ。

Object.opCmp はデフォルトで実行時エラー

D 0.163
Jul 18, 2006
New/Changed Features

  • Object.opCmp now throws an error. Should override it if used. Breaks existing code.
  • Imports now default to private instead of public. Breaks existing code.
  • Added static imports, renamed imports, and selective importing.

これもたいした変更ではないですが.

当該ドキュメント: http://www.digitalmars.com/d/operatoroverloading.html

D言語には,opCmp と opEquall が両方存在します.
その理由として,

・等値性は大小関係のチェックよりもしばしば簡単に実装できる
・オブジェクトによっては大小関係に意味がないので比較行為をエラー扱いにするため opCmp を次のようにオーバーライドすることが推奨される;

class A
{
int opCmp(Object o)
{
assert(0); // 比較は意味をなさない
return 0;
}
}

ということになっていました.
この実装がデフォルトになったので,オーバーライドが推奨じゃなくて強制されるようになった,と考えてよいでしょう.
opCmp のオーバーライドの例はこちら.

import std.stdio;

class Integer
{
int value;

int opCmp(Integer other)
{
if( this.value < other.value )
{
return -1;
}
else if( this.value > other.value )
{
return 1;
}
else
{
return 0;
}
}
}

void main()
{
auto x = new Integer;
auto y = new Integer;
x.value = 10;
y.value = 20;

if( x > y )
{
writefln("x > y");
}
else if( x < y )
{
writefln("x < y");
}
else
{
writefln("x == y");
}
}

参考: http://wisdom.sakura.ne.jp/programming/d/d17.html

このサンプルで opCmp をコメントアウトすると確かにエラーになり,

Error: need opCmp for class Integer

と実行時に表示されるようになります.