mrrational
mrrational
MModular
Created by mrrational on 8/2/2024 in #questions
How to overload methods of generic structs to target particular types
Consider the snippet below:
struct Wrapper[T: CollectionElement]:
var value: T

fn __init__(inout self, value: T):
self.value = value

var j = Wrapper[Float64](32.0)
var i = Wrapper[Int](42)
struct Wrapper[T: CollectionElement]:
var value: T

fn __init__(inout self, value: T):
self.value = value

var j = Wrapper[Float64](32.0)
var i = Wrapper[Int](42)
I would like to add a get_decimal method which dispatches differently based on the type of T. For example if T is Int it should return False and True if T is a Float64 I have tried something like below and get a Compiler Error:
struct Wrapper[T: CollectionElement]:
var value: T

fn __init__(inout self, value: T):
self.value = value

fn has_decimal(self: Wrapper[Float64]) -> Bool:
return True
struct Wrapper[T: CollectionElement]:
var value: T

fn __init__(inout self, value: T):
self.value = value

fn has_decimal(self: Wrapper[Float64]) -> Bool:
return True
The Error:
error: 'self' argument must have type 'Wrapper[T]', but actually has type 'Wrapper[SIMD[float64, 1]]'
fn has_decimal(self: Wrapper[Float64]) -> Bool:
^ ~~~~~~~~~~~~~~~~
mojo: error: failed to parse the provided Mojo source module
error: 'self' argument must have type 'Wrapper[T]', but actually has type 'Wrapper[SIMD[float64, 1]]'
fn has_decimal(self: Wrapper[Float64]) -> Bool:
^ ~~~~~~~~~~~~~~~~
mojo: error: failed to parse the provided Mojo source module
Thanks in advance for the help
6 replies