const/invariant member function (2)
前にconstメンバ関数周りの挙動を調べたことがあるのだけど,丁度今2chのスレが盛り上がってるみたいなので改めて調査.
まず,D言語 2.0 でのメンバ関数の const int func(); は,C++ の const メンバ関数になる.
C++ のコードで言うとこれ;
class A { int func() const; };
つまり, const を付ける位置が前と後ろという違いがある.
それを踏まえて,次のD言語 2.0 のコードを試す;
import std.stdio; class A { const int s; const(int) t; const const(int) u; // エラーにならず const(int) と解釈される const int a() {return 1;} // constメンバ関数 const(int) b() {return 1;} const const(int) c() {return 1;} // constメンバ関数 } void main() { const int i; const(int) j; const const(int) k; // エラーにならず const(int) と解釈される writefln(typeid(typeof(i))); // const(int) writefln(typeid(typeof(j))); // const(int) writefln(typeid(typeof(k))); // const(int) A x = new A; writefln(typeid(typeof(x.s))); // const(int) writefln(typeid(typeof(x.t))); // const(int) writefln(typeid(typeof(x.u))); // const(int) // 関数の戻り値の「型」を見てみる writefln(typeid(typeof(x.a()))); // int <----------------- writefln(typeid(typeof(x.b()))); // const(int) writefln(typeid(typeof(x.c()))); // const(int) // この2つはいつもエラー: redundant storage class 'const' // const const int i; // const const int func(); }
ローカル変数と,メンバ変数の場合は,const int も const(int) も同じ意味になる.
メンバ関数の場合は,const int func() と const(int) func() が違う意味になるので注意.
ちょっとはまりやすいかもしれないですね.