Overload ** in C ++

In Python, we have a nice simple syntax to take an arbitrary int / float value. Namely, for you who are not Python programmers, we can have the following statement:

y = 2 ** 3 print y 

This will print 8 on the console and has good syntax since there is a built-in β€œpower” statement. Is it possible to overload "**" as a single statement in C ++? In particular, I want to do something like this:

 int a = 2; int b = 3; cout << (a**b) << endl; 

or, if this is not possible, something like this:

 MyInt a = new MyInt(2); // Wrapper class around ints to play nicely with ** MyInt b = new MyInt(3); cout << (a**b) << end; // Assume ostream overridden for MyInt 

They should also print 8 for the console. I understand that it would be much easier to redefine the ^ operator to do the same, but what interests me most is if I can overload the **. Will the operator "*" (for the case of the class MyInt, if it is a member function), have to see if the argument was another "*", since I do not know how to specify "**" as a single operator? Is it even possible to pass an operator as an argument?

Additional / bonus condition, if possible (as if I had not said enough): No macros !!!

+5
source share
2 answers

Do you mean something like this?

 #include <iostream> #include <cmath> struct MyInt { int val; struct MyProxy { int val; }; MyProxy operator *() const{ return MyProxy{val}; } MyInt operator * (const MyProxy& b) { return MyInt{ static_cast<int>(std::pow(val, b.val)) }; } }; std::ostream& operator << (std::ostream& o, const MyInt& m) { return o << m.val; } int main(){ MyInt a{5}, b{3}; std::cout << a**b << std::endl; } 

See here live http://coliru.stacked-crooked.com/a/ab56b9cd6e422e12

Explanation:

  • Overload the unary operator * to return a proxy object
  • Overload the binary operator * to use the proxy server ... Simple :-)
  • I used a proxy class to avoid subtle errors.

C ++ is fun ... I want to believe that you do it for fun, not in production ... Because its a very bad idea in production, just call std::pow

+4
source

Short answer: None. There is no way to "overload" arbitrary sequences of characters / tokens in C ++.

The longer answer: a**b equivalent to a * (*b) , so you can overload both binary * (i.e., multiply) and unary * (i.e., dereferencing) in some rude way. But that would be completely opaque / unexpected for anyone reading your code, and would be painful for debugging / support in the future.

Just write a function called pow() !

+4
source

Source: https://habr.com/ru/post/1245943/


All Articles