-1

I am aware about operator overloading, but this is not what I am talking about.

I do quite a bit of scientific computation in C++. So for example I have to compute gradients, dot products, laplacians, hessians...

All of these usually have well defined and standrad math symbols. The gradient uses nabla, the hessian nabla^2 the laplacian \delta ...

I normally have to write vec Gradient(fun_ptr) or Hessian(fun_ptr).

The issues is that this makes the code deviate from the paper I am implementing and it makes it just a little harder to catch when you copied something wrong.

Is there any way to define the \nabla character as an operator for example?

Makogan
  • 8,208
  • 7
  • 44
  • 112
  • 1
    These days you can use `UTF-8` characters in function names (on some compilers at least), so you can use greek letters for functions and/or constants. Eg `double π = 3.14;` – Galik Feb 19 '22 at 21:16
  • One issue with operators is precedence. You can't set the precedence level for new operators, it has to be hardwired in the compiler. – Thomas Matthews Feb 19 '22 at 21:58
  • It can be sort-of-kind-of done in C++, here's an infix [pwr](https://stackoverflow.com/q/36356668/4641116) operator. As a toy proof-of-concept, but not as a serious solution. It'd be non-idiomatic C++. There's also another way using [macros](https://stackoverflow.com/questions/15632217/defining-new-infix-operators), also not recommended for serious code. – Eljay Feb 20 '22 at 15:26

1 Answers1

2

Is there a way to define operators in C++?

No. You can only overload (some of) the existing operators for custom types in C++.

You can define functions that implement the operations that you want, and if you encode your source code in a character set that has those symbols (i.e. you use Unicode), and your compiler supports it (which isn't guaranteed since the symbols aren't part of the basic character set), then you can use the symbols as names of those functions. But you cannot call the functions with infix notation in C++.

(or another language)

You can define infix functions in Haskell.

eerorika
  • 232,697
  • 12
  • 197
  • 326