Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在boost::lambda中使用boost::format_C++_Boost Lambda_Boost Format - Fatal编程技术网

C++ 在boost::lambda中使用boost::format

C++ 在boost::lambda中使用boost::format,c++,boost-lambda,boost-format,C++,Boost Lambda,Boost Format,由于某些原因,我未能在boost::lambda中使用boost::format。下面是我的代码(希望)的可编译简化: #include <algorithm> #include <iomanip> #include <iostream> #include <boost/assign/list_of.hpp> #include <boost/format.hpp> #include <boost/lambda/lambda.hp

由于某些原因,我未能在
boost::lambda
中使用
boost::format
。下面是我的代码(希望)的可编译简化:

#include <algorithm>
#include <iomanip>
#include <iostream>

#include <boost/assign/list_of.hpp>
#include <boost/format.hpp>
#include <boost/lambda/lambda.hpp>

namespace bl = boost::lambda;

int main()
{
    const std::vector<int> v = boost::assign::list_of(1)(2)(3);
    std::for_each(v.begin(), v.end(), bl::var(std::cout) << std::setw(10) << bl::_1);
    std::for_each(v.begin(), v.end(), bl::var(std::cout) << boost::format("%10d") % bl::_1);
}
#包括
#包括
#包括
#包括
#包括
#包括
名称空间bl=boost::lambda;
int main()
{
const std::vector v=boost::assign::list_of(1)(2)(3);

std::for_each(v.begin()、v.end()、bl::var(std::cout)我敢打赌,您遇到了这样一个事实:使用的格式不再可用

boost::format f("...");

std::string s = f % ... ;
std::string s2 = f % other options...; // FAIL!  f has been changed by the above use!
换句话说,在一种格式上使用%实际上会将字符串数据替换为你在其中输入的任何内容。更酷的是,上面的第二次使用会自动失败


我知道,这有点违反直觉,但事实就是如此。

出于某种原因,您的代码会立即计算
boost::format(“%10d”)%bl:_1,而不是每次调用lambda

为了防止这种情况,您需要在调用
bl::var
时包装
boost::format(“%10d”)
,就像您使用
std::cout
所做的那样

不幸的是,这样做需要Boost.Lambda来推断对
操作符%
的调用的返回类型,这是它无法做到的。因此必须使用
bl::ret
显式指定返回类型。请注意,此返回类型必须是引用,以便
std::cout
直接访问返回的对象而不是它的副本

因此,我们得到以下代码,生成预期的输出:

std::for_each(v.begin(), v.end(), bl::var(std::cout) <<
    bl::ret<const boost::format &>(bl::var(boost::format("%10d")) % bl::_1));

std::for_each(v.begin()、v.end()、bl::var(std::cout)感谢您的回答,但我相信您提供的代码工作正常。引用boost.format文档“一旦提供了所有参数,您就可以将format对象转储到流。[…]在传递另一个参数之前,结果字符串在format对象中保持可访问状态,然后重新初始化。”第二个
%
确实重新初始化了格式,但对我来说,这应该是一件好事!根据我的经验,这不是好事,但如果你的数量不同,我建议忽略我的回答。不知道你还有什么问题。是的,这是可行的,但我不知道为什么有必要这样做!
boost::lambda::var
应该只是必要的当两个参数都不是lambda表达式时,我的目标是使用
boost::lambda
:(太糟糕了