I think the easiest solution here is to not define ex separately, but inside the generated function. You can then use $$ to interpolate twice, meaning the interpolated variable lives in the scope of Op2, like OP, A and B, or just interpolate once with $ to interpolate variables from the generated function’s scope, like T:
julia> macro Op2(OP,A,B)
return esc(quote
@generated function $OP(a::MyType{Ta},b::MyType{Tb}) where{Ta,Tb}
T = max(Ta,Tb)
return :(MyType{$T}($$OP(a.x*$$A,b.x*$$B)))
end
end)
end
@Op2 (macro with 1 method)
julia> struct MyType{T} x end
julia> @Op2 Base.:+ 1 2
julia> MyType{1}(1) + MyType{2}(2)
MyType{2}(5)