输入到 stringstream 并在单个语句中转换为字符串。没有助手 class 可能吗?
input to stringstream and convert to string in single statement. Possible without helper class?
我想这样写代码:
std::string s = ??? << "asdf" << 123;
我不确定要放置什么才能让 ???
正常工作。我可以写一个助手 class:
#include <string>
#include <sstream>
#include <iostream>
struct Stringify {
std::stringstream o;
template <typename T>
Stringify& operator<<(const T& t){
o << t;
return *this;
}
operator std::string(){ return o.str(); }
};
int main(){
std::string s;
s = Stringify() << " test " << 123 << " asd";
std::cout << s << std::endl;
}
...但我无法在没有助手 class 的情况下完成此操作。我尝试了不同的方法,这是我从中得到的最好的错误消息:
s = (std::stringstream() << "test" << 123 << " asd").str();
-> error: ‘class std::basic_ostream<char>’ has no member named ‘str’
我也尝试了更多,但它只是导致更复杂的错误消息。
是否可以在不编写帮助程序的情况下做我想做的事情class?如果不是,是否有任何充分的理由说明为什么仅使用 std
东西是不可能的?
像这样:
std::string s = static_cast<std::ostringstream&>(std::ostringstream() << 7 << 10 << 12).str();
我想这样写代码:
std::string s = ??? << "asdf" << 123;
我不确定要放置什么才能让 ???
正常工作。我可以写一个助手 class:
#include <string>
#include <sstream>
#include <iostream>
struct Stringify {
std::stringstream o;
template <typename T>
Stringify& operator<<(const T& t){
o << t;
return *this;
}
operator std::string(){ return o.str(); }
};
int main(){
std::string s;
s = Stringify() << " test " << 123 << " asd";
std::cout << s << std::endl;
}
...但我无法在没有助手 class 的情况下完成此操作。我尝试了不同的方法,这是我从中得到的最好的错误消息:
s = (std::stringstream() << "test" << 123 << " asd").str();
-> error: ‘class std::basic_ostream<char>’ has no member named ‘str’
我也尝试了更多,但它只是导致更复杂的错误消息。
是否可以在不编写帮助程序的情况下做我想做的事情class?如果不是,是否有任何充分的理由说明为什么仅使用 std
东西是不可能的?
像这样:
std::string s = static_cast<std::ostringstream&>(std::ostringstream() << 7 << 10 << 12).str();