简体   繁体   中英

How to override ToString() in an SRTP class

I am having issues creating a generic math class (here as very tiny example code a class of type Vector) that, however, is not limited to one single numerical data type for its values, but instead uses ^F as static resolved type parameter , and I expect it to be whatever the user uses to instanciate the class, such as int but also BigRational or MyCustomNumber , as long as it adheres to the constraints.

type Vector< ^F> (_values : ^F []) =
    let values = _values
    member inline __.Dimension = Array.length values
    member inline __.Item with get i = values.[i + 1]
    static member inline ( * ) (a: Vector< ^F>) (scalar: ^F) =
        Vector< ^F>(Array.init (a.Dimension) (fun i -> values.[i] * scalar)
    override inline __.ToString() = "{" + (values.ToString()) + "}" // <--- problem-line

My problem now with this code is, that I still don't know how to properly override the Object.ToString() method (same for how to implement IComparable, which I believe I could fix the same way).

Is this actually even possible?

Many thanks in advance!

  • Do not annotate the arithmetic operator's arguments with a type parameter, they will be inferred alright
  • Pass the arguments of the arithmetic operator as a tuple
  • Close the parenthesis in the implementation of the arithmetic operator
  • Replace the let -bound value values by a property
type Vector<'F> (_values : 'F[]) =
    member val Values = _values
    member inline me.Dimension = Array.length me.Values
    member inline me.Item with get i = me.Values.[i + 1]
    static member inline ( * ) (a: Vector<_>, scalar) =
        Vector<_>(Array.init (a.Dimension) (fun i -> a.Values.[i] * scalar))
    override me.ToString() = "{" + (me.Values.ToString()) + "}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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