F#:强制转换为泛型类型 [英] F#: Casting to generic type

查看:151
本文介绍了F#:强制转换为泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是F#的新手,来自C ++背景。我试图写一个简单的向量类,它可以是通用类型(int,float等),但我遇到麻烦的默认构造函数。我想将值初始化为零,但这样做我需要以某种方式将一个具体的零一个通用类型,但我不知道如何做到这一点。

I'm fairly new to F# and coming from a C++ background. I am trying to write a simple vector class which can be of generic type (int, float, etc) but I run into trouble with the default constructor. I want to initialize the values to be zero but to do this I need to somehow cast a concrete zero to a generic type but I'm not sure how to do this.

也许有些代码可能会有帮助。这是我到目前为止:

Perhaps some code might help. Here's what I have so far:

type Vector3D<'T> (x :'T, y: 'T, z: 'T) = 
    member this.x = x
    member this.y = y
    member this.z = z

    new() = Vector3D<'T>(0,0,0) // what goes here?

我已经在突出显示的行上尝试了很多事情,但似乎不能让编译器满意。我尝试,例如, Vector3D('T 0,'T 0,'T 0),我认为应该施放 int 零到'T 零但不起作用。

I have tried many things on the highlighted line but cannot seem to get the compiler to be happy. I tried, for instance, Vector3D('T 0, 'T 0, 'T 0) which I thought should cast the int zero to 'T zero but that did not work.

我缺少一些基本的东西,只是一个获得正确语法的情况?

Am I missing something fundamental or is it merely a case of getting the right syntax?

推荐答案

这里是一个使用内置的通用零函数的解决方案:

Here's a solution which uses the built-in generic zero function:

type Vector3D<'T> (x : 'T, y: 'T, z: 'T) =
    member this.x = x
    member this.y = y
    member this.z = z

let inline newVector () : Vector3D<_> =
    let zero = Core.LanguagePrimitives.GenericZero
    Vector3D(zero, zero, zero)

let v1 : Vector3D<int> = newVector ()
let v2 : Vector3D<double> = newVector ()
let v3 : Vector3D<int64> = newVector ()

这篇关于F#:强制转换为泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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