提升图书馆格式; 获取std :: string

moo*_*020 13 c++ boost

我想添加一些我使用boost库格式化的字符串,如下所示

boost::container::vector<std::string> someStringVector;
someStringVector.push_back(
    format("after is x:%f y:%f and before is x:%f y:%f\r\n") % 
    temp.x %
    temp.y %
    this->body->GetPosition().x %
    this->body->GetPosition().y;
Run Code Online (Sandbox Code Playgroud)

编译器抱怨它无法转换类型,我尝试将.str()附加到格式返回的末尾,但它仍然抱怨.

我得到的错误信息是:

error C2664: 'void boost::container::vector<T>::push_back(
  const std::basic_string<_Elem,_Traits,_Ax> &)' :
  cannot convert parameter 1 from
    'boost::basic_format<Ch>' to 
    'const std::basic_string<_Elem,_Traits,_Ax> &'
Run Code Online (Sandbox Code Playgroud)

有人有见识吗?

Ben*_*ley 20

你需要在调用boost :: str时包装格式,如下所示:

str( format("after is x:%f y:%f and before is x:%f y:%f\r\n")
     % temp.x % temp.y % this->body->GetPosition().x % this->body->GetPosition().y)
Run Code Online (Sandbox Code Playgroud)


zda*_*dan 6

在生成的格式对象中添加".str()"就足够了(对我来说很有用).从你的问题确切地说你是如何做到这一点并不清楚,但我确实注意到你的例子缺少了push_back()上的关闭parens.

请注意,您要对从最后一个%运算符返回的格式对象调用str(),最简单的方法是将整个格式行包装在parens中,如下所示:

boost::container::vector<std::string> someStringVector;
someStringVector.push_back(
    (format("after is x:%f y:%f and before is x:%f y:%f\r\n") % 
    temp.x %
    temp.y %
    this->body->GetPosition().x %
    this->body->GetPosition().y).str() );
Run Code Online (Sandbox Code Playgroud)