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
4 Replies
gabrieldemarmiesse
The only way I found currently is to pass an additional parameter and do a bitcast. See https://github.com/modularml/mojo/pull/3349 which does this
GitHub
[stdlib] Use memcpy in List._realloc for x13.2 speedups in some b...
Currently, when re-allocating a list, elements are moved one by one. While it is correct, when one knows that T is a trivial type, we an use memcpy thus giving massive speedups in some benchmarks. ...
mrrational
mrrational2mo ago
erm that seems like a too specific solution? Like what if I want to do it on other complex types I defined. Also, is this supposed to change because I think all of this can still be handled at the compile time itself?
gabrieldemarmiesse
that's the only solution I could find while we wait for a proper solution in the language
mrrational
mrrational2mo ago
Thanks for sharing!
Want results from more Discord servers?
Add your server