Does D have 'newtype'?

后端 未结 2 1008
夕颜
夕颜 2021-02-14 17:22

Does D have \'newtype\' (as in Haskell).

It\'s a naive question, as I\'m just skimming D, but Google didn\'t turn up anything useful.

In Haskell this is a way of

2条回答
  •  心在旅途
    2021-02-14 18:00

    In D1.0 there is typedef, which is the strong typing from a predefined type to a 'newtype.'

    D2.0 has removed this and only alias remains (what typedef is in C). There is talk about having a wrapper template that can strongly create a new type.

    The issue with typedef was that there were good arguments for making the newtype a sub-type of the predefined type, and also good arguments for making it a super-type.

    The semantics of typedef are that the base type is implicitly converted to the newtype, but the newtype is not converted to the base type or other types with the same base type. I am using base type here since:

    typedef int Fish;
    typedef Fish Cat;
    Fish gold = 1;
    Cat fluff = gold;
    

    Will fail to compile.

    And as of right now, 2.048 DMD still allows the use of typedef (but don't use it).

    Having the base type convert to the newtype is useful so you don't have to write

    meters = cast(meters) 12.7;
    

提交回复
热议问题