Home > Software engineering >  Is there a way to initialize object, call its method, then pass it as function argument, in just the
Is there a way to initialize object, call its method, then pass it as function argument, in just the

Time:06-10

Is there a way to initialize an object, call a few of its method (it is not possible to just construct the object to be in the needed state), then pass it as an argument to a function, and possibly one-liner, just in the calling scope? Something like this:

#include <iostream>
#include <sstream>
void log(const std::ostringstream& obj) {
    std::cout<<obj.str();
    //Do something meaningful with obj that doesn't modify it
}
void gol(const std::string& obj) {
    std::cout<<obj;
    //Do something meaningful with obj that doesn't modify it
} 
int main() {
    log(std::ostringstream oss << "Foo" << 123 << 'B');
    gol(std::string str .append("Foo").append(std::to_string(123)).append("Bar"));
}

By "in the calling scope", I mean that the object "oss" is automatically destroyed after "log" returns. The same goes for "str".

I could do it like this:

int main() {
     {
        std::ostringstream oss;
        oss << "Foo" << 123 << 'B';
        log(oss);
     }
     {
        std::string str;
        str.append("Foo").append(std::to_string(123)).append("Bar"));
        gol(str);
     }
}

But then it's not really one-liner anymore.

CodePudding user response:

You can write it like this:

#include <iostream>
#include <sstream>
void log(const std::ostringstream& obj) {
    std::cout<<obj.str();
    //Do something meaningful with obj that doesn't modify it
}
void gol(const std::string& obj) {
    std::cout<<obj;
    //Do something meaningful with obj that doesn't modify it
} 
int main() {
    log(std::ostringstream{} << "Foo" << 123 << 'B');
    gol(std::string{}.append("Foo").append(std::to_string(123)).append("Bar"));
}

Though, I am not aware of a way to give it a name, call methods, and pass it to another function, all in the same expression.

In general, trying to squeeze as much code into a single line is not something that is actually desirable.

  • Related