Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost Library Format; getting std::string

Tags:

c++

boost

I want to add some string which I format using the boost library as follows

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;

The compiler is complaining that it can't convert types, and I tried appending .str() to the end of what format returns, but it still complained.

The error message I got was:

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> &'

Anyone have some insight?

like image 947
moowiz2020 Avatar asked Nov 12 '10 19:11

moowiz2020


2 Answers

You need to wrap the format in a call to boost::str, like so:

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)
like image 76
Benjamin Lindley Avatar answered Nov 07 '22 22:11

Benjamin Lindley


Adding a ".str()" to the resulting format object should be enough (and works for me). It is not clear from your question exactly how you did so, but I did notice that your example is missing the closing parens on the push_back().

Note that you want to call str() on the format object returned from the last % operator, the easiest way to do so is to just wrap the whole format line in parens like so:

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() );
like image 43
zdan Avatar answered Nov 07 '22 22:11

zdan