boost::lambda::if_then 用于 copy_if
我一直在尝试通过以下代码模拟 copy_if 但我的编译器(g++-4.0)只是不断抱怨。 技术上有什么问题? 感谢您的帮助!
template <class STL> // a std container of class A, but I don't know if it's a list or vector or deque
void export_(STL& Alist) { //a member function
for_each(Alist0.begin(), Alist0.end(), //member data
boost::lambda::if_then(
boost::lambda::bind(&A::get_StatusTag, boost::lambda::_1) == OK, //some global enum returned by A::get_StatusTag
boost::lambda::bind(&STL::push_back, Alist, boost::lambda::_1)
)
);
}
I have been trying to emulate a copy_if by the following codes but my compiler (g++-4.0) just keeps complaining. What's technically wrong? Thanks for your help!
template <class STL> // a std container of class A, but I don't know if it's a list or vector or deque
void export_(STL& Alist) { //a member function
for_each(Alist0.begin(), Alist0.end(), //member data
boost::lambda::if_then(
boost::lambda::bind(&A::get_StatusTag, boost::lambda::_1) == OK, //some global enum returned by A::get_StatusTag
boost::lambda::bind(&STL::push_back, Alist, boost::lambda::_1)
)
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
lambda::bind 通过复制进行绑定。 表达式
bind(&STL::push_back, AList, _1)
因此创建了一个包含AList副本的函子。 由于该函子的operator()是const,所以应用它会失败,因为它最终会调用const对象(其内部副本)上的非常量成员(push_back)。解决方案:绑定到 AList 的引用,使用:
bind(&STL::push_back, boost::ref(AList), _1)
lambda::bind binds by copy. The expression
bind(&STL::push_back, AList, _1)
thus creates a functor holding a copy of AList. Since this functor's operator() is const, applying it fails because it ends up calling a non-const member (push_back) on a const object (its internal copy).Solution: bind to a reference to AList, using:
bind(&STL::push_back, boost::ref(AList), _1)
作为参考,这里有一个更正常的 copy_if 实现,取自 http://www.richelbilderbeek.nl/CppCopy_if .htm
然后你可以像这样使用它:
当然假设我复制的行不是代码中失败的行。
For reference, here's a more normal implementation of copy_if, taken from http://www.richelbilderbeek.nl/CppCopy_if.htm
Then you'd use it like:
Assuming of course that the line I've copied isn't the line which fails in your code.
我的猜测是编译器不喜欢这行代码,
我想知道它是否未能从绑定对象而不是 _1 中找到正确的运算符方法。 您应该尝试将其包装在另一个 lambda 表达式中。
可以这样想:
My guess is the compiler does not like the line
I wonder if it's failing to find the right operator method from the bind object and not the _1. You should try wrapping it in another lambda expression.
Think of it this way: