Minor style question: promotion inside constructor and new

This is a minor style question: I have a solution but it is a bit convoluted, and I wonder how others do it.

Suppose I want to cache something precomputed in a struct in the constructor (this is the only constructor, an inner one, and ensures that all instances are valid). At the same time, I would like to promote all fields to be the same type (to avoid unnecessary type proliferation).

MWE:

struct Example{T}
    a::T
    b::T
    c::T                        # a/b, saved
    function Example(a::T, b::T) where {T}
        c = a / b
        args = promote(a, b, c)           # how to do this
        new{typeof(first(args))}(args...) # in a simpler way
    end
end

Example(1, 2)

Instead of typeof(first(promote(a,b,c))) you could use promote_type(T,typeof(c)).

2 Likes

But then I would still need to promote(a, b, c) for the new.

Actually no. They will be converted by default, so

struct Example{T}
           a::T
           b::T
           c::T                        # a/b, saved
           function Example(a::T, b::T) where {T}
               c = a / b
               new{promote_type(T,typeof(c))}(a,b,c)
           end
       end

should work.

4 Likes

Indeed it does. I missed it in the docs. Thanks!

1 Like