简体   繁体   English

D有'newtype'吗?

[英]Does D have 'newtype'?

Does D have 'newtype' (as in Haskell). D是否具有'newtype'(如在Haskell中)。

It's a naive question, as I'm just skimming D, but Google didn't turn up anything useful. 这是一个天真的问题,因为我只是在浏览D,但谷歌没有发现任何有用的东西。

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. 在Haskell中,这是一种在编译时使不同类型的相同事物不同的方法,但不会导致任何运行时性能损失。

eg 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). 如果您的程序以米为单位以数秒为单位添加数量,那么在编译时会出错,但在运行时会像在两者中一样快(它们在运行时)。

If D doesn't have something analogous to 'newtype', what are the accepted methods for dealing with dimensioned quantities? 如果D没有类似'newtype'的东西,那么处理尺寸数量的方法有哪些?

Thanks, 谢谢,

Chris. 克里斯。

In D1.0 there is typedef, which is the strong typing from a predefined type to a 'newtype.' 在D1.0中有typedef,它是从预定义类型到'newtype'的强类型。

D2.0 has removed this and only alias remains (what typedef is in C). D2.0删除了这个,只剩下别名(C中的typedef)。 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. typedef的问题在于,有一个很好的参数可以使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. typedef的语义是基类型被隐式转换为newtype,但newtype不会转换为基类型或具有相同基类型的其他类型。 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). 目前,2.048 DMD仍允许使用typedef(但不要使用它)。

Having the base type convert to the newtype is useful so you don't have to write 将基类型转换为newtype非常有用,因此您无需编写

meters = cast(meters) 12.7;

Funny, as he_the_great mentions, D1 had a strong typedef but noone used it, possibly because it was impossible to customize the exact semantics for each case. 有趣的是,正如他提到的那样,D1有一个强大的typedef但没有人使用它,可能是因为无法为每个案例定制确切的语义。 Possibly the simplest way to handle this situation, at least for primitive types, is to include a mixin template somewhere in Phobos that allows you to forward all operators but have the boilerplate to do this automatically generated via the mixin. 处理这种情况的最简单方法,至少对于原始类型,可能是在Phobos中的某个地方包含一个mixin模板,它允许你转发所有操作符,但是有通过mixin自动生成的样板。 Then you'd just create a wrapper struct and be all set. 然后你只需创建一个包装器结构并完成所有设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM