Search code examples
c++method-chainingsyntactic-sugarfunction-callsmember-functions

Is there a way to call multiple functions on the same object with one line?


Just trying to tidy up a program and was wondering if anyone could feed me some syntax sugar with regard to calling a member function on one queue multiple times on the same line.

For example, changing:

queue<int> q;
q.push(0);
q.push(1);

to something like:

q.(push(0), push(1));
//or
q.push(0).push(1);

I know it looks a little ridiculous, and it isn't practical. But if I wanted to shorten a small portion of code like that, is there an option to do so? From what I've read so far, it's only possible to chain methods when the function has a non-void return value.

Of course, this is an option:

q.push(0); q.push(1);

But I'm trying to avoid having q there twice. Again... syntactic sugar :)

The goal here is not to initialize, but to condense the number of times an object/container is brought up in a block of code. The reason I'm referencing a queue is because it's dynamic.


Solution

  • If you have a class that you can modify, make the function return a reference to itself:

    template<typename T>
    class queue {
    public:
        //...
        queue& push(T data) {
            //...
            return *this; //return current instance
        }
        //...
    private:
        //...
    };
    

    Then you can do

    queue<int> q;
    q.push(0).push(1);
    

    If you can't, then your hands are tied. You could make a wrapper around the class, but to save a few characters, this is hardly worth the effort.

    In your case with push, you can do:

    queue<int> q = { 0, 1 };
    

    But this obviously only works with push, as the queue will contain 0 and 1 after the 2 push's.