D有“新类型”吗? [英] Does D have 'newtype'?

查看:84
本文介绍了D有“新类型”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

D是否有'newtype'(如在Haskell中一样)。

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

这是一个天真的问题,因为我只是略读D,但Google并未出现有用的东西。

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

在Haskell中,这是一种使不同类型的同一事物在编译时有所区别的方式,但不会导致任何运行时性能损失。

In Haskell this is a way of making different types of the same thing distinct at compile time, but without incurring any runtime performance penalties.

例如您可以将米,秒和公斤设置为新类型(双精度)。如果您的程序将以米为单位的数量添加到以秒为单位的数量中,则在编译时会出错,但是在运行时就像两个都是double一样快(它们在运行时)。

e.g. you could make newtypes (doubles) for metres, seconds and kilograms. This would error at compile time if your program added a quantity in metres to a quantity in seconds, but would be just as fast at runtime as if both were doubles (which they are at runtime).

如果D没有类似于'newtype'的东西,那么处理维数的可接受方法是什么?

If D doesn't have something analogous to 'newtype', what are the accepted methods for dealing with dimensioned quantities?

谢谢

Chris。

推荐答案

在D1.0中有typedef,这是从预定义类型到'newtype'的强类型。

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

D2.0已删除它,仅保留别名(C中的typedef)。有人谈论拥有一个可以强烈创建新类型的包装器模板。

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.

typedef的问题在于,有很好的论据使newtype成为子类型的子类型。

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.

typedef的语义是将基本类型隐式转换为newtype,但将newtype隐式转换为newtype。不会转换为基本类型或具有相同基本类型的其他类型。我在这里使用基本类型,因为:

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;

将无法编译。

截至目前,2.048 DMD仍允许使用typedef(但不要使用它)。

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;

这篇关于D有“新类型”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆