C++ Logo

std-proposals

Advanced search

Introduce `operator function`

From: Владимир Прокофьев <vov-crao_at_[hidden]>
Date: Tue, 25 Feb 2020 23:05:11 +0300
I have a proposal for the operator of function.

Imagine the completed and finished struct which we cannot modify without breaking compatibility.

file: a.h

    struct A
    {
        int a1 = 0;
        int a2 = 0;
    
    public:
        int GetA1() const { return a1; }
        int GetA2() const { return a2; }
    };

I need to add a new functional for this struct and add a new function to perform some actions under object of this struct:
Because struct A is declared in a file which we cannot modify, I have to declare a separate function:

    int diff(const A& a)
    {
        return a.a1 - a.a2;
    }

and use it as like a regular function:

     A a;

    int d = diff(a);

with the new `operator function` it will look like:

       // same as
    // int diff(const &A a)
    // {
    // return a.a1 - a.a2;
    // }
    operator int(const A& a) diff
    {
        return a.a1 - a.a2;
    }

    int d = a.diff();

This is a sintax sugar, but it helps to make code simpler.

It can be confusing with some sort of arguments:

    operator int(A* a) base
    {
        return a->a1 + a->a2;
    }

    A *aa = &a;
    int d = aa.base(); // use `.` notation with a pointer

It supports inheritance:

    struct B : A
    {
        int d;
    };

    int d = b.diff();

----------

The `operator function` brings another kind of object - multiple.

    struct C
    {
        int c;
    };

    // same as
    // int mult(const A& a, const C& c)
    // {
    //    return a.diff() * c.c;
    // }
    operator int(const A& a, const C& c) mult
    {
        return a.diff() * c.c;
    }

It can be used when several objects are combined to perform some common action(s):
  
    A a;
    C c;
    
    int m = [a,c] .mult();

    auto o = [a,c];
    int m = o.mult();

// work with `o` like with a single object.

// int m = mult(a,c);

The ` operator function ` allow extending any frozen functional without intervention
into the complete code, but it makes code looks like already provides desired functional with
additional declaration.

With best regards.
Vladimir

----------------------------------------------------------------------

Received on 2020-02-25 14:07:55