...ing logging 4.0

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

デリゲートと関数ポインタ

デリゲートと関数ポインタとの違いがややこしいので,メモしとこ.

D言語のデリゲートは,C#と違って複数の関数を登録して一度に呼び出すことはできないようだ.
要するに,スタティックな関数は関数ポインタで,非スタティックな関数はデリゲートで扱うらしい.
これってどうなんやろ,デリゲートの有効性がいまいちわかっていないからどうしようもないけど,何が嬉しいのかなぁ.
C++メンバ関数ポインタとかややこしいから,それがデリゲートという形になったのは嬉しいのかもしれない.
でもやっぱり勉強不足なのでよくわからんな.
あー.


class TestClass
{
public:
// These functions return input value directly.
int nonStaticFunc(int a) { return a; }
static int staticFunc(int a) { return a; }
}

int main(char[][] args)
{
// Delegate
TestClass event = new TestClass;
int delegate(int) d = &event.nonStaticFunc;
// int delegate(int) ed1 = &event.staticFunc; // <-- Compile error
// int delegate(int) ed2 = &TestClass.staticFunc; // <-- Compile error

// Function pointer
int function(int) f = &TestClass.staticFunc;
int function(int) ef1 = &TestClass.nonStaticFunc;
// int function(int) ef2 = &event.nonStaticFunc; // <-- Compile error

printf("delegate: d(1)=%d\n", d(1));
printf("function pointer: f(2)=%d\n", f(2));
// printf("function pointer: ef1(10)=%d\n", ef1(10)); // <-- Runtime error

return 0;
}

出力結果


delegate: d(1)=1
function pointer: f(2)=2