Home > Software design >  A Chain adding function
A Chain adding function

Time:10-20

I have a questions on where to even start on this problem. The problem requires the following.

/*We want to create a function that will add numbers together when called in succession.*/

add(1)(2); // == 3

I have never seen functions be used in such a way and I am currently at a loss of where to start. I tried to do some research on parameter chaining, but this is all I could find.

https://levelup.gitconnected.com/how-to-implement-method-chaining-in-c-3ec9f255972a

If you guys have any questions I can edit my code or question. Any help is appreciated.

CodePudding user response:

.... way and I am currently at a loss of where to start?

One way, is to start with an anonymous (unnamed) functor, which has operator(), that returns the reference to the this, as follows:

struct {  // unnamed struct
    int result{ 0 };

    auto& operator()(const int val) noexcept
    {
        result  = val;
        return *this;   // return the instance itself
    }
    // conversion operator, for converting struct to an int
    operator int() { return result; }

} add;  // instance of the unnamed struct


int main() 
{
    std::cout << add(1)(2); // prints:  3
}

See a live demo


Read more about the unnamed structs, functors and conversion operator here:

CodePudding user response:

The trick is to overload operator() and use a proxy object.

struct LhsAddProxy
{
   int lhs_;
   int operator()(int rhs) const { return lhs_   rhs; }
};

LhsAddProxy add(int lhs) { return {lhs}; }
  • Related