How to make a worded operator?

Is there a way to use letters instead of signs for operators?
1
2
3
4
5
6
7
class MyClass {
    public:
    int x;
    MyClass(int a){this->x=x;}
    int operator + (MyClass c){return x+c.x;} //how you would normally do.
    int operator add(MyClass c){return x+c.x;} //why can't I do this?
};

So that then I can use it like:
1
2
3
MyClass a(5);
MyClass b(9);
int c = a add b;

Last edited on
To my knowledge, you can only over ride operators that are already present in the c++ language. Which means you can not create new operators.

Of course... You can always use #define add +
C++ has a few "worded" operators: and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq. No "add"
A comma-delimited worded operator; really a ,add, operator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

template < typename T > struct grab_arg1
{
    grab_arg1( const T& f ) : arg1(f) {}
    const T& arg1 ;
};

struct add_ {} add ; 

template < typename T > grab_arg1<T> operator, ( const T& v, add_ )
{ return grab_arg1<T>(v) ; }

template < typename T, typename U >
auto operator, ( const grab_arg1<T>& g, const U& arg2 ) -> decltype(g.arg1+arg2)
{ return g.arg1 + arg2 ; }

int main()
{
    double a = 1.8 ;
    int b = 4 ;
    std::cout << ( a, add, b ) << '\n' ; // a + b
    long c = 78 ;
    std::cout << ( a, add, b, add, c ) << '\n' ; // a + b + c
    std::cout << ( "abcdefgh", add, b ) << '\n' ; // "abcdefgh" + b
}

A comma-delimited worded operator; really a ,add, operator:


My brain just exploded.
Topic archived. No new replies allowed.