Boost库格式;获取std::string

18

我想添加一些字符串,我使用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;
编译器报错,指出无法转换类型。我尝试在format返回值后添加.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> &'

有人有一些见解吗?


5
编译器通常以错误信息的形式进行指示,你遇到了哪些错误信息?请提供相关信息。 - James McNellis
将对boost :: format的调用包装在boost :: str中怎么样? - Anonymous
2个回答

27

你需要将格式字符串包装在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)

当我这样做时,它会给我一个错误:错误 C2440:“返回”:无法将“std :: string”转换为“std :: basic_string <_ Elem,_ Traits,_ Ax> &&”。 - moowiz2020
@moowiz2020:someStringArray是什么类型?请提供完整的类型规范,包括模板参数。 - Benjamin Lindley
这是一个 boost::container::vectorstd::string。 - moowiz2020

8
将“.str()”添加到结果格式对象中应该就足够了(对我来说有效)。从你的问题中并不清楚你是如何做到这一点的,但我注意到你的示例中缺少push_back()的闭合括号。
请注意,您想要在最后一个%运算符返回的格式对象上调用str(),最简单的方法是将整个格式行用括号括起来,如下所示:
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() );

我将您的代码复制粘贴到程序中,但是出现了错误:错误 C2440: 'return' : 无法将类型为'std::string'的值转换为'std::basic_string<_Elem,_Traits,_Ax> &&'。可能是编译器特定的问题。 - moowiz2020
@moowiz2020:我使用的是VS 2008。也许你需要提供一个完整的示例来展示问题。 - zdan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接