使用 boost::lambda 调用成员函数
我正在学习 boost::lambda
库,为此我编写了此示例代码以将 vector
转换为 vector
通过从 A
对象中提取值。
class A
{
public:
A(int n) : m_n(n){}
int get() const {return m_n;}
private:
int m_n;
};
int _tmain(int argc, _TCHAR* argv[])
{
using namespace boost::lambda;
std::vector<A> a1;
std::vector<int> a2;
a1.push_back(A(10));
a1.push_back(A(20));
std::for_each(a1.begin(), a1.end(), bind(&std::vector<int>::push_back, var(a2), bind(&A::get, _1)));
return 0;
}
经过多次尝试,我可以让 for_each
部分正常工作。但我仍然不喜欢那些多重绑定。有没有其他方法可以写这个。最好我想做一些类似的事情:a2.push_back(bind(&A::get,_1));
,但这不能编译。
I am learning the boost::lambda
library and for that I wrote this sample code to convert an vector<A>
into vector<int>
by extracting the value from A
object.
class A
{
public:
A(int n) : m_n(n){}
int get() const {return m_n;}
private:
int m_n;
};
int _tmain(int argc, _TCHAR* argv[])
{
using namespace boost::lambda;
std::vector<A> a1;
std::vector<int> a2;
a1.push_back(A(10));
a1.push_back(A(20));
std::for_each(a1.begin(), a1.end(), bind(&std::vector<int>::push_back, var(a2), bind(&A::get, _1)));
return 0;
}
I could get the for_each
part to work after several tries. But I still don't look the like of it with those multiple binds. Is there any other way to write this. Preferably I would like to do something like: a2.push_back(bind(&A::get,_1));
, but that doesn't compile.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你想做的事情是不可能的。
for_each
将函数应用于范围中的每个元素,但您试图调用两个成员函数,并且必须将它们都绑定。我认为您的代码是使用for_each
时可以做的最好的事情。 Lambda 文档对我来说看起来非常完整,但没有您想要执行的操作的示例。我认为这是有原因的,有一个更合适的算法。正如基里尔所说,这是变换
。I don't think what you're trying to do is possible.
for_each
applies function to each element in the range, but you are trying to call two member functions and you'll have to bind them both. I think your code is the best you can do when usingfor_each
. Lambda documentation looks very complete to me, but there is no example for what you're trying to do. I think it's for a reason, there is a more appropriate algorithm for this. As Kirill said it'stransform
.