如“成员变量作为目标”部分所述:
指向成员变量的指针并不是真正的函数,但 [ boost::lambda::bind
] 函数的第一个参数仍然可以是指向成员变量的指针。调用这样的绑定表达式会返回对数据成员的引用。
因此,要构造访问z
成员的 lambda 表达式,您可以使用:
boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1)
返回的对象本身可以在其他表达式中使用。例如,
boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1) = 0.0
意思是“获取第一个参数(type)的成员的double
引用并赋值0.0”。z
Imath::V3f&
然后,您可以将此 lambda 与 Boost.Function 和std::for_each
:
boost::function<void(Imath::V3f&)> f = boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1) = 0.0;
std::for_each(vec.begin(), vec.end(), f);
作为参考,这里有一个完整的、可编译的示例:
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <boost/function.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
namespace Imath
{
class V3f
{
public:
double x, y, z;
V3f(double x_, double y_, double z_)
: x(x_), y(y_), z(z_)
{
}
friend std::ostream& operator<<(std::ostream& os, const V3f& pt) {
return (os << '(' << pt.x << ", " << pt.y << ", " << pt.z << ')');
}
};
}
int main()
{
std::vector<Imath::V3f> vec(5, Imath::V3f(1.0, 1.0, 1.0));
boost::function<void(Imath::V3f&)> f = boost::lambda::bind(&Imath::V3f::z, boost::lambda::_1) = 0.0;
std::for_each(vec.begin(), vec.end(), f);
std::vector<Imath::V3f>::iterator it, end = vec.end();
for (it = vec.begin(); it != end; ++it) {
std::cout << *it << std::endl;
}
return EXIT_SUCCESS;
}
输出:
(1, 1, 0)
(1, 1, 0)
(1, 1, 0)
(1, 1, 0)
(1, 1, 0)