Generate type specific code when type is a variable in a loop

Maybe this will give you some inspiration.

julia> macro add_description(num)
           T = esc(Symbol("Container$num"))
           f = esc(:description)
           desc_str = Symbol("description$num")
           quote
               struct $T end
               $f(::Type{$T}) = $desc_str
               $f(::Val{$num}) = $desc_str
           end
       end
@add_description (macro with 1 method)

julia> const description8 = "Eight is the best"               "Eight is the best"

julia> const description42 = "Answer to the Ultimate Question of Life, the Universe, and Everything"
"Answer to the Ultimate Question of Life, the Universe, and Everything"

julia> @add_description(8)
description (generic function with 2 methods)

julia> @add_description(42)
description (generic function with 4 methods)

julia> description(Container8)
"Eight is the best"

julia> description(Container42)
"Answer to the Ultimate Question of Life, the Universe, and Everything"

julia> description(Val(8))
"Eight is the best"

julia> description(Val(42))
"Answer to the Ultimate Question of Life, the Universe, and Everything"
1 Like