输入到stringstream并在单个语句中转换为字符串。可能没有助手类?

时间:2017-04-13 08:55:27

标签: c++ string stringstream

我想写这样的代码:

std::string s = ??? << "asdf" << 123;

我不确定要让???使其正常工作。我可以写一个帮助类:

#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;   
}

...但是我无法在助手班上做到这一点。我尝试了不同的东西,这是我从中得到的最好的错误信息:

  s =  (std::stringstream() << "test" << 123 << " asd").str();

  -> error: ‘class std::basic_ostream<char>’ has no member named ‘str’

我也尝试了更多,但它只是导致更复杂的错误消息。

是否可以在不写辅助类的情况下做我想做的事情?如果没有,是否有任何充分的理由说明为什么只能用std个东西?

1 个答案:

答案 0 :(得分:3)

这样的事情:

std::string s = static_cast<std::ostringstream&>(std::ostringstream() << 7 << 10 << 12).str();