# Overloading \`^\`

**URL:** <https://discourse.julialang.org/t/overloading/119723>\
**Category:** New to Julia\
**Tags:** operator, overloading\
**Created:** [September 23, 2024, 1:59am UTC](https://discourse.julialang.org/t/overloading/119723 "2024-09-23T01:59:50Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sadish-d](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/sadish-d/32/48058_2.png) [@sadish-d](https://discourse.julialang.org/u/sadish-d)\
**Post date:** [September 23, 2024, 1:59am UTC](https://discourse.julialang.org/t/overloading/119723/1 "2024-09-23T01:59:50Z")

</div>

```julia
struct S x end
Base.:(^)(s::S, p) = S(s.x ^ p)
S(1) ^ -2.0
S(1) ^ -2 # ERROR: MethodError: no method matching inv(::S)

```

It looks like you can not completely define `^` for a type, without defining a multiplicative inverse `inv`. Does anybody know what else it needs? Is there a better way to overload operators without leaving bugs like this behind?

---

<div class="post-metadata">

**Author:** ![nsajko](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nsajko/32/221187_2.png) [@nsajko](https://discourse.julialang.org/u/nsajko)\
**Post date:** [September 23, 2024, 2:09am UTC](https://discourse.julialang.org/t/overloading/119723/2 "2024-09-23T02:09:27Z")

</div>

See the `^` doc string. In short, `S(1) ^ -2` isn’t calling `^`, it’s calling a different function, `literal_pow`. This is an ugly special case implemented at an early stage of compilation. It applies **only** to `^`, not to any other function, thankfully.

The workaround is to do, for example, `S(1) ^ Int(-2)` instead.

BTW, `literal_pow` isn’t public. If you must overload it, guard it behind an `isdefined(Base, :literal_pow)`.

---

<div class="post-metadata">

**Author:** ![kapple](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kapple/32/218915_2.png) [@kapple](https://discourse.julialang.org/u/kapple)\
**Post date:** [September 23, 2024, 2:49am UTC](https://discourse.julialang.org/t/overloading/119723/3 "2024-09-23T02:49:33Z")

</div>

Interestingly NaNMath.jl defines functions with the same names as Base (or other respective stdlib packages e.g. Statistics.jl) except that it defines `pow` instead of dealing with `^` or even `literal_pow`.
