Logical const in D

前端 未结 5 1425
情书的邮戳
情书的邮戳 2020-12-06 16:54

D has two types of constness: immutable variables are ones that were declared immutable, and always will be immutable, while const variables are simply rea

5条回答
  •  無奈伤痛
    2020-12-06 17:50

    Being a pragmatic language, D has the ability to cast away const if you really need to. I think the following should work:

    class M {
      bool set;
      real val;
    
      real D() const {
        if(!set) {
          M m = cast(M)this;
          m.val = this.some_fn();
          m.set = true;
        }
        return this.val;
      }
    }
    

提交回复
热议问题