使用 std::vector;使用 boost::bind
在尝试熟悉 boost
时,遇到了将 boost::function
与 std::vector
一起使用的问题。我正在尝试做一件简单的事情:拥有一个具有相似签名的函数列表,然后在示例数据上使用所有这些函数和 std::for_each
。这是代码:
typedef boost::function<int (const char*)> text_processor;
typedef std::vector<text_processor> text_processors;
text_processors processors;
processors.push_back(std::atoi);
processors.push_back(std::strlen);
const char data[] = "123";
std::for_each(processors.begin(), processors.end(),
std::cout << boost::bind(&text_processors::value_type::operator(), _1, data)
<< "\n"
);
因此,使用 for_each
我尝试将每个函数应用于样本数据的结果写入标准输出。但它不会像这样编译(一些关于 bind
结果缺少运算符 <<
的长消息)。
如果我删除流运算符,那么我将获得可编译但无用的代码。诀窍是我想在单个 for_each
中执行函数应用和文本输出。我缺少什么?认为使用 lambda 或类似的东西应该很容易,但无法找出正确的解决方案。
While trying to get comfortable with boost
, stumbled into problem with using boost::function
along with std::vector
. I'm trying to do a simple thing: have a list of functions with similair signatures and then use all that functions with std::for_each
on sample data. Here is the code:
typedef boost::function<int (const char*)> text_processor;
typedef std::vector<text_processor> text_processors;
text_processors processors;
processors.push_back(std::atoi);
processors.push_back(std::strlen);
const char data[] = "123";
std::for_each(processors.begin(), processors.end(),
std::cout << boost::bind(&text_processors::value_type::operator(), _1, data)
<< "\n"
);
So, with for_each
I'm trying to write to standard output the result of applying every function to sample data. But it won't compile like this (some long message about missing operator <<
for bind
result).
If I remove stream operators then I'll have compilable, but useless code. The trick is that I want to do function applying and text output in single for_each
. What am I missing? Thought it should be easy with lambdas or smth like that, but can't figure out the correct solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码的问题在于您试图以不允许的方式创建一个仿函数(您不能只在
for_each
的第三个参数处抛出代码,您需要传递 函子)。如果编译器中没有 lambda 支持,您可以使用
std::transform
而不是std::for_each
(未经测试...但这应该可行):如果您的编译器支持 lambda你可以用它来做:
但是你可以完全避免
bind
:The problem with your code is that you are trying to create a functor in place in a way that is not allowed (you cannot just throw code at the third argument of
for_each
, you need to pass a functor).Without lambda support in the compiler you can use
std::transform
rather thanstd::for_each
(not tested... but this should work):If your compiler supports lambdas you can do with it:
But then you can avoid the
bind
altogether: