Matt Galaxy Matt Galaxy - 8 months ago 35
C++ Question

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;

to something like:

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-
return value.

Of course, this is an option:

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

But I'm trying to avoid having
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 of it's dynamic.


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

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

Then you can do

queue<int> q;

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 obiously only works with push, as the queue will contain 0 and 1 after the 2 push's.