Operators - redefinition

closed account (jvqpDjzh)
//Hi! How would you redefine this operator to make it do exponential operations?
//this is my attempt, that doesn't work! I admit: I have little experience in redefining operators

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include <iostream>
using namespace std;

template <typename T>
T operator^(T base, int exp)
{
    //recursive solution
    if(exp == 0)
        return 1;
    else
        return ( base * operator^(base, exp - 1) );
}

int main()
{
    double c = 3 ^ 2;//doesn't work!
    return 0;
}
Last edited on
C++ has builtin bitwise XOR operator ^ that takes integral operands.

You essentially have this:
1
2
3
4
5
6
7
8
9
void foo( int ); // concrete function

template <typename T>
void foo( T ); // template for overloads


int main() {
  foo( 42 ); // Which foo() to call?
}

I know that Herb Sutter has written quite a lot about how the "Which foo() to call?" is resolved in various situations, but I cannot remember the details. In short: there are many surprises.
Use std::pow from <cmath>

You cannot overload operators where all arguments are primitive types.
Last edited on
closed account (jvqpDjzh)

keskiverto (1965)

Yes, know that ^ is the XOR operator that takes integral operands, even though at this time I don't remember clearly and exactly how to use it... basically means that just one has to be true...


Which foo() to call?

Maybe it's because it's late, but what has it to do with my question? (lol)
Last edited on
closed account (jvqpDjzh)
LB

Thank you for remembering me about pow(), but ofc my intention was to try to create my pow using the overloading of the operator ^.
Pity we can't overload operators where all args are primitive type.. But what exactly are the rules?
closed account (jvqpDjzh)
lol
Topic archived. No new replies allowed.