有没有办法初始化对象,调用其方法,然后在函数呼叫范围中以函数参数的形式传递给它?
有没有一种方法来初始化对象,调用其一些方法(不可能仅构造对象以处于所需的状态),然后将其作为参数传递给函数,甚至可能是单线在通话范围中?类似的事情:
#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"));
}
通过“在调用范围”中,我的意思是“ oss”对象在“日志”返回后自动销毁。 “ str”也是如此。
我可以这样做:
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);
}
}
但是那不是真正的单线。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以这样写它:
不过,我不知道给它命名,调用方法并将其传递给另一个功能的方法。
通常,试图将尽可能多的代码挤入一行并不是真正需要的东西。
You can write it like this:
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.