Equivalent of Python in C++ operator

763 Views Asked by At

Is there a way to do the same in C++?

Python

int.__add__(1, 1)

I can make something in C++, but it is still ugly and not very optimised and short.

I just want this : 1+1, but without + . I absolutely want to use the int "class".

It's for matrix multiplication, addition, and subtraction... I just want to have better-looking and shorter code.

2

There are 2 best solutions below

0
n. m. could be an AI On

I can make something in C++, but it is still ugly and not very optimised and short.

Last time I checked, int.__add__(1, 1) was way longer than 1+1. Just about anything is longer than 1+1. As for optimisations, you are not in a position to talk about what is more optimised, having not measured anything.

It's for matrix multiplication, addition, and subtraction

The same integer + operator is useful in lots of contexts. Matrix operations are among them. There is no need to single them out.

I just want this : 1+1, but without +

What you want is of secondary importance. Programming is a team sport. You do what everyone else does. Not only because it is likely to be tried and tested and the best thing after the sliced bread, but also because if everyone is doing something in a particular way and you are doing it differently, others will find it hard to understand what you mean.

This is not to say you cannot break conventions and introduce innovations. People do it all the time. But they are not asking anyone how to! If you need to ask, you are not in a position to lead the crowd.

I just want to have better-looking and shorter code.

Then absolutely positively use +. A no-brainer.

0
Matthias Fripp On

You want to use a function (or functor) for addition instead of the + operator. C++ has std::plus for that. I don't use C++ but I think one or both of these should work:

int a = std::plus(1, 1);
int a = std::plus<int>(1, 1);