Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static operator overloading

Is it possible to overload C++ class operators in the static context? e.g.

class Class_1{ ... }
int main()
{

    Class_1[val]...

}
like image 267
jameszhao00 Avatar asked Sep 07 '09 18:09

jameszhao00


People also ask

Can operator overloading static?

Operator overloading is an example of static polymorphism. You can leverage operator overloading or to add functionality to operators so as to work with user defined types much the same way you work with fundamental data types.

Can you overload an operator in C?

C does not support overloading of operators or functions. There's no way you can redefine < , <= , > , >= , == , or != to compare struct types directly.

Can an operator be static?

The function call operator or operator template is declared static if the lambda-expression has no lambda-capture, otherwise it is non-static.

What does <= mean in C++?

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.


2 Answers

If you are looking for metaprogramming using the built-in operator: Such a thing isn't possible - the built-in operators operate on runtime values, not on compile time values.

You may use boost::mpl for that, and instead of using the built-in operators, use its templates, like at for op[], plus<a, b> for op+ etc.

int main() {
    using boost::mpl::vector;
    using boost::mpl::at_c;
    using boost::mpl::plus;
    using boost::mpl::int_;

    typedef vector<int, bool, char, float> Class_1;
    typedef vector< int_<1>, int_<2> > Numeric_1;

    at_c<Class_1, 0>::type six = 6;
    typedef plus<at_c<Numeric_1, 0>::type 
                ,at_c<Numeric_1, 1>::type>::type r;
    int i3[r::value] = { 4, 5, 6 };
    return ((i3[0] + i3[1] + i3[2]) * six) == 90;
}
like image 110
Johannes Schaub - litb Avatar answered Oct 07 '22 09:10

Johannes Schaub - litb


I don't believe it's possible, though I could be wrong on this front. I'd like to ask why you'd want to do this though. Rather than performing operations on a class instead of instances, perhaps you just require one instance throughout your application? In this case, you should probably be using the singleton pattern.

like image 21
Samir Talwar Avatar answered Oct 07 '22 11:10

Samir Talwar